【发布时间】:2011-11-30 00:43:32
【问题描述】:
我有以下 Javascript,我在其中修改了标准 Google Maps API 的 initialize() 函数和标准的 addMarker 函数。地图加载并居中正常,但标记未添加到地图中。我查看了 previous question ,但我不确定我做错了什么..
<script type="text/javascript">
// Note that using Google Gears requires loading the Javascript
// at http://code.google.com/apis/gears/gears_init.js
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var usa = new google.maps.LatLng(44.58, -95.46); //middle of the US w 50 states
var browserSupportFlag = new Boolean();
function initialize() {
var myOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions)
map.setCenter(usa);
}
function getMyLocation() {
var initialLocation= newyork;
var myOptions = {
zoom: 10,
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);
addMarker(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
// Try Google Gears Geolocation
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
addMarker(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(usa);
}
}
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map,
title: "Hello World!"
});
//markersArray.push(marker);
}
</script>
【问题讨论】:
-
您没有在任何地方调用 getLocation 函数,因此为什么 addMarker 也没有被调用...
-
getLocation 函数在我按下按钮时被调用。
-
啊,好吧,在这种情况下,如果您发布整个代码会有所帮助。
标签: javascript google-maps google-maps-api-3