繁体   English   中英

多个页面刷新时加载Google Maps Api V3

[英]Google Maps Api V3 load on multiple page refreshes

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

在body 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM