【问题标题】:Creating Google Maps LatLng classes dynamically动态创建 Google Maps LatLng 类
【发布时间】:2014-12-05 09:52:55
【问题描述】:

我正在尝试使用谷歌自己的 API 在谷歌地图上创建标记。我的问题是我正在从文本文件中读取 JSON 数据,然后尝试将其分解为纬度和经度,以便我可以在地图上放置标记。你可以在下面看到我的代码。

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。我相信他们的构造语句有问题,但不确定到底出了什么问题。如果我在某些坐标中硬编码它也不起作用。谢谢您的帮助!

【问题讨论】:

  • 在从文件中获取 lat long 值后尝试添加一个 console.log() 语句,并查看它们在传递给 LatLng 函数时是什么。
  • A google.maps.LatLng 对象接受两个数字作为参数,而不是包含两个用逗号分隔的数字字符串的字符串...

标签: javascript google-maps google-maps-api-3


【解决方案1】:

a 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”来验证它们是有效数字。

【讨论】:

    【解决方案2】:

    pictureLocations,你使用的方式是数组...输出为字符串,试试...

    var tempPictureLocation = pictureLocations.join(" ");
    

    虽然,这可能行不通,因为我不确定是什么...

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

    ... 使用此代码放入数组中。

    【讨论】:

    • 感谢您的帮助,我刚刚解决了它。我不需要引号中的逗号。
    • 我可能会错过,但这是有道理的!
    【解决方案3】:

    Google Maps LatLng 构造函数设计用于在数字之间使用逗号,因此看起来像这样:pictureLocations[i] = new google.maps.LatLng(tempLat, tempLong);

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 2020-11-02
      • 2013-11-08
      • 2022-06-15
      相关资源
      最近更新 更多