谷歌地图 API V3 在多次页面刷新时加载



我有这个脚本来初始化谷歌地图。初始化函数初始化映射。问题是它可以工作,但不是第一次打开页面。我必须刷新它两到三次才能显示地图。为什么会这样?

正在主体 OnLoad 事件上调用初始化函数。

而且它不会在除 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);           
    });
}

我说这是因为地理位置何时返回是未知的。它是异步的。如果地图尝试在地理位置完成之前加载,则不会设置变量latitudelongitude,并且不会加载地图。

确保地理位置首先进行,它应该没问题。

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>

最新更新