2014-12-05 94 views
0

我試圖在谷歌地圖上使用谷歌自己的API創建標記。我的問題是,我正在從文本文件中讀取JSON數據,然後嘗試將其分解爲緯度和經度,以便我可以在地圖上放置標記。你可以在下面看到我的代碼。動態創建Google地圖LatLng類

var oReq = new XMLHttpRequest(); //New request object 
oReq.onload = function() { 
//This is where you handle what to do with the response. 
//The actual data is found on this.responseText 
//alert(this.responseText); //Will alert: the location latitude and longitude in JSON 

locations = JSON.parse(this.responseText); 
//alert(locations); 
for(var i = 0; i < locations.length; i++){ 
    var tempLocation = locations[i]; 
    //alert(tempLocation); 

    var tempLat = tempLocation.latitude; 
    var tempLong = tempLocation.longitude; 
    tempLat = tempLat.toString(); 
    tempLong = tempLong.toString(); 

    pictureLocations[i] = new google.maps.LatLng(tempLat + ", " + tempLong); 
} 
    var tempPictureLocation = pictureLocations.toString(); 
    alert(tempPictureLocation); 

}; 

我的問題是變量pictureLocations返回NaN。我相信他們在我的構建聲明中有些問題,但不確定究竟是什麼問題。如果我在某些座標中硬編碼,它也不起作用。謝謝您的幫助!

+0

嘗試添加一個console.log()語句,當你從文件中獲得lat long值並查看它們傳遞給LatLng函數時它們是什麼。 – getbuckts 2014-12-05 01:46:00

+0

[google.maps.LatLng](https://developers.google.com/maps/documentation/javascript/reference#LatLng)對象以兩個數字作爲參數,而不是包含由逗號分隔的兩個數字字符串的字符串。 – geocodezip 2014-12-05 01:47:46

+0

[解析數據到谷歌地圖]可能的重複(http://stackoverflow.com/questions/18464174/parsing-data-onto-google-map/18466611#18466611) – geocodezip 2014-12-05 01:54:05

回答

2

一個google.maps.LatLng object需要兩個數字作爲參數。這是不正確的:

pictureLocations[i] = new google.maps.LatLng(tempLat + ", " + tempLong); 

應該

pictureLocations[i] = new google.maps.LatLng(tempLat,tempLong); 

,更安全的是:

pictureLocations[i] = new google.maps.LatLng(
          parseFloat(tempLocation.latitude), 
          parseFloat(tempLocation.longitude)); 

從JSON來了,他們都是字符串。您甚至可以在使用它們構建google.maps.LatLng之前通過測試「isNaN」來驗證它們是有效的數字。

0

pictureLocations,你使用它的方式是一個數組...作爲一個字符串輸出,嘗試...

var tempPictureLocation = pictureLocations.join(" "); 

雖然,因爲我不知道這是什麼可能無法正常工作......使用此代碼將數組放入數組中。

+0

感謝您的幫助,我剛剛解決了它。我不需要引號中的逗號。 – Matt 2014-12-05 01:45:51

+0

我可能會錯過的,但它是有道理的! – rfornal 2014-12-05 01:46:37

0

谷歌地圖經緯度構造是專爲arguement有號碼之間用逗號,所以它看起來是這樣的:pictureLocations[i] = new google.maps.LatLng(tempLat, tempLong);