当放置在 map 初始化位置之外的函数中时,我很难为我的 map 分配标记。
我有一个固定的标记,它在加载 map 时放置,效果很好。我还希望在访问该页面的用户的位置放置一个标记。我已将第二部分放在一个名为 getUserLocation() 的单独函数中。
我试过在 getUserLocation() 函数中调用 getMap() 函数,但它不起作用。我假设我所追求的是可能的?示例如下。
// Get user location
function getUserLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// Users location
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log(pos);
var userLocationMarker = new google.maps.Marker({ map: map, position: pos });
getMap();
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
}
// Initialise Google Maps
function getMap() {
var mapOptions = {
center: {lat: 50.7367030, lng: -3.5171710},
zoom: 13
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Home marker
var marker = new google.maps.Marker({
map: map,
position: {lat: 50.7367030, lng: -3.5171710}
});
}
最佳答案
我昨天刚回答了一个关于标记的类似问题here .
我只是根据您的需要对其进行了编辑。
$('#button').click(function() {
addmarker('-22.3157017', '-49.0660877');
});
$('#button2').click(function() {
addmarker('-23.5936152', '-46.5856465');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button" style="width:80px;height:30px;cursor:pointer;">
Click
</button>
<button id="button2" style="width:80px;height:30px;cursor:pointer;">
Click2
</button>
<div id="map" style="width:555px;height:500px"></div>
<script>
function getMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(50.7367030, -3.5171710),
zoom: 13
});
addmarker(50.7367030, -3.5171710);
}
function addmarker(lat, lon) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map
});
map.panTo(marker.getPosition());
}
function getUserLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//call function sending coordinates
addmarker(position.coords.latitude, position.coords.longitude)
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDL5dMHBCV7crlostybmkuGBAXjOP3yawQ&callback=getMap"></script>
关于javascript - 谷歌地图 API 在函数之间传递信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43661732/