Google Maps API JS - 从另一个JS文件访问标记位置

问题描述 投票:-1回答:1

我需要使用放置标记的位置,以便能够通过另一个API加载天气数据。我让我的地图放下一个加载并放下一个标记以及一个对象“myPosition”,它应该包含标记的lat和lon。我的问题是使用标记的坐标更新myPosition.lat和.lng。下面是我到目前为止的代码,我能够从另一个文件中的myPosition获取初始化数据,但我无法弄清楚如何获取坐标。这是我第一次使用HTML和JS而且我通常使用C ++或Java,这对我来说有点变化。

var myPosition = 
{
lat: 0,
lng: 0
}; 

function initMap()
{
var texas = {lat: 32.7767, lng: -96.7970};
var map = new google.maps.Map(document.getElementById('map'), 
{
    zoom: 10,
    center: texas
});

var marker = new google.maps.Marker({
    position: texas,
    map: map
});

google.maps.event.addListener(map, 'click', function(event)
{
    placeMarker(event.latLng);
});

function placeMarker(location)
{ 
    if (marker == undefined)
    {
        marker = new google.maps.Marker(
        {
            position: location,
            map: map, 
            animation: google.maps.Animation.DROP,
        });
    }
    else
    {
        marker.setPosition(location);
    }

map.setCenter(location);
}
}
javascript html google-maps google-maps-api-3 global
1个回答
0
投票

听起来你需要的是考虑问题而不是你的“其他文件”访问坐标,更多的是通过回调通知你的其他模块鼠标点击地图。

例如。在weather.js

function handleCoords(latlng){
   //...Do whatever you want with latlng
}

// Export function as needed if you're using modules/webpack.
// (don't worry if you don't know what this means)

然后在你的嵌入式HTML嵌入式JS中的main.js

// import {handleCoords} from './weather'
// Again ignore this if you're not using modules/don't know what this means.

google.maps.event.addListener(map, 'click', function(event){
    placeMarker(event.latLng);
    handleCoords(event.latLng); // This is how you pass the latlng 
                                       // along to weather.js 

});
© www.soinside.com 2019 - 2024. All rights reserved.