我是Javascript和Google地图的新用户,我正在尝试使用Google Developers网站上提供的信息为地图添加标记。虽然地图在当前位置显示,但我在Javascript控制台上没有出现任何错误,但由于某种原因,标记仍未显示。有关为什么会发生这种情况的任何想法?提前谢谢。
这是我的代码:
function initialize() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
// Browser doesn't support Geolocation
else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag == true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
initialLocation = siberia;
}
map.setCenter(initialLocation);
}
var marker = new google.maps.Marker({
position: initialLocation,
title:"You are here!"
});
// should add the marker to the map
marker.setMap(map);
};
答案 0 :(得分:0)
地理定位服务是异步的。您需要使用其回调函数内的坐标。很难说你发布了地理定位采用的路径,这里的代码如果成功就可以实现。
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
position: initialLocation,
title:"You are here!"
});
// should add the marker to the map
marker.setMap(map);
}, function() {
handleNoGeolocation(browserSupportFlag);
});