[英]Javascript Google Maps v3 API - can't add marker
我是Java語言和Google Maps的新手,我正嘗試使用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);
};
地理位置服務是異步的。 您需要在其回調函數中使用坐標。 很難從您發布的內容中分辨出地理位置所采用的路徑,以下是成功執行代碼的代碼。
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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.