【问题标题】:Google Geocode Javascript API - How to get coordinates?Google Geocode Javascript API - 如何获取坐标?
【发布时间】:2015-11-07 05:26:10
【问题描述】:

我希望 Google 地图将用户提交的地址转换为地图坐标。我只希望将这些坐标存储在一个变量中,以便以后访问:

function map_search() {
    console.log("search form functional"); // sanity check
    var searchLoc = $('#search_location').val();
    console.log(searchLoc);
    var searchCoords = geocoder.geocode( {'address': searchLoc});
    console.log(searchCoords);

    ...
}

我是这样设置的:

var geocoder = new google.maps.Geocoder();

这直到定义var seachCoords 为止。在控制台中,它只是打印为undefined

其他 Google 地图功能在此页面上运行成功。 是我的 JavaScript 错误,还是我不正确地使用了这个地理编码器?

【问题讨论】:

  • 到底是什么问题?

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


【解决方案1】:

来自https://developers.google.com/maps/documentation/javascript/geocoding的文档

地理编码服务需要在检索地理编码器结果时执行回调方法。此回调应按顺序传递两个参数来保存结果和一个状态代码。

示例:

geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        console.log(results); // all results
        console.log(results[0].geometry.location); // "first" location
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });

注意:这本质上是异步,所以不要试图把它放在一个在 return 语句中返回 results[0].geometry.location 的函数中

【讨论】:

  • 好的。我不想创建标记,但我想我可以尝试使用这种策略通过 POST 请求发送坐标,这就是我想要做的。感谢您的发现。
  • 我发布了文档中的确切代码 - 我将进行编辑以免混淆问题
  • 谢谢 :) 如果我在这里保存我的变量,是应该保存它以供以后使用,还是我需要将我的 POST ajax 代码包装在这个函数中?
  • 将其保存在全局中,或使用回调,或使用承诺 - 选择权在您手中
  • 是的,异步位让我失望。当它保存变量时,需要它的函数已经失败了。
【解决方案2】:

试试这个 php 脚本:

function getCoordinates($address){

$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern

$url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=$address";

$response = file_get_contents($url);

$json = json_decode($response,TRUE); //generate array object from the response from the web

return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);

}

如何在php中调用函数:

echo getCoordinates('740 Story Rd San Jose CA 95122');
Result : 37.328865,-121.8581845

【讨论】:

  • 哇。我以前从未使用过 PHP。在实施之前我应该​​花一些时间来学习。
  • PHP 是服务器端 - 这甚至是一个答案
  • 哈哈,我是这么认为的。我没有使用 PHP。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 2018-10-24
  • 1970-01-01
相关资源
最近更新 更多