2012-05-05 152 views
0

我有這個腳本初始化谷歌地圖。初始化函數初始化地圖。問題是,它的工作原理,但不是第一次頁面打開時。我要刷新它會出現兩到三次地圖。爲什麼這樣呢?谷歌地圖Api V3加載多個頁面刷新

正文OnLoad事件正在調用初始化函數。

並且還沒有在任何其他瀏覽器中加載除鉻(後兩到三個頁面刷新)

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

我說,這是因爲它是未知的,當地理位置的回報。它是異步的。如果地圖嘗試在地理位置完成之前加載,則變量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> 
+0

日Thnx它的工作,但在Chrome但仍然沒有出現在其他瀏覽器,爲什麼???起來 – Mj1992

+0

我試着在Firefox 12.0(工作),歌劇(沒有工作),我沒有最近的IE瀏覽器。你會得到「geoloc錯誤?」我試圖弄清楚如何從錯誤中提取更多信息。我會用我發現的任何東西更新 –

+0

我等了一會兒,地圖顯示出來了。它在歌劇中也有效。 – Mj1992