0

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

在正文 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);           

    });

}
4

1 回答 1

0

我说这是因为地理定位何时返回是未知的。它是异步的。如果地图尝试在地理定位完成之前加载,则变量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>
于 2012-05-05T17:10:40.733 回答