我有这个脚本来初始化谷歌地图。初始化函数初始化地图。问题是它工作但不是第一次页面打开时。我要刷新它两到三次地图到出现。为什么会这样?
正在身体OnLoad事件上调用initialize函数。
并且它除了chrome之外没有加载任何其他浏览器(在两到三页刷新之后)
var infowindow = new google.maps.InfoWindow();
var places=[]; //contains the addresses of markers
//Find User GeoLocation to Show On Map for the First TIme Map opens.
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition)
}
else
{
alert("Geolocation is not supported by this browser.");
}
function showPosition(position)
{
latitude=position.coords.latitude;
longitude= position.coords.longitude;
}
//Initialize Google Map Api
function initialize()
{
geocoder = new google.maps.Geocoder();
//Initial Map Variables
var myoptions={
zoom:8,
center:new google.maps.LatLng(latitude,longitude),
mapTypeId:google.maps.MapTypeId.ROADMAP
};
//Initialize Map
map=new google.maps.Map(document.getElementById("map_canvas"),myoptions);
});
}
答案 0 :(得分:0)
我说这是因为当地理位置返回时它是未知的。它是异步的。如果地图尝试在地理定位完成之前加载,则不会设置变量latitude
和longitude
,并且不会加载地图。
确保地理位置优先,并且应该没问题。
https://files.nyu.edu/hc742/public/googlemaps/stackload.html
function getLocation() {
var infowindow = new google.maps.InfoWindow();
var places=[]; //contains the addresses of markers
//Find User GeoLocation to Show On Map for the First TIme Map opens.
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition, function(err) { alert(err + " " + err.code);});
}
else
{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position)
{
latitude=position.coords.latitude;
longitude= position.coords.longitude;
initialize(latitude, longitude);
}
//Initialize Google Map Api
function initialize(latitude, longitude)
{
geocoder = new google.maps.Geocoder();
//Initial Map Variables
var myoptions={
zoom:8,
center:new google.maps.LatLng(latitude,longitude),
mapTypeId:google.maps.MapTypeId.ROADMAP
};
//Initialize Map
map=new google.maps.Map(document.getElementById("map_canvas"),myoptions);
}
HTML:
<body onload="getLocation()">
<div id="map_canvas"></div>
</body>