【问题标题】:Google Geocode API result displaying on map?Google Geocode API 结果显示在地图上?
【发布时间】:2010-11-21 14:26:49
【问题描述】:

我正在阅读 Google 的 API,但没有看到任何示例,所有其他 Google 搜索的示例都有些陈旧(大约 1-2 岁,大多数是基于 API 密钥的 :S)。

我想要一个文本输入。发送按钮。和下面的 iframe。

如何使用我自己的输入在地图上显示位置?

此时我的 iframe 看起来像这样:

<iframe width="230" height="180" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="<?php echo $src ?>">

输入:

<input id="googleMaps" name="googleMaps" type="text" />

此时我正在尝试使用 XML(但据我所知推荐使用 JSON?),但我在 iframe 中获取的 XML 只是文本,例如:

This document had no style information.
<GeocodeResponse>
<status>
OK
</status>
<result>
<type>
locality
</type>
<type>
political
</type>
<formatted_address>
(...)

如何将这些数据传递给 Google 并取回地图? :)

非常感谢。

【问题讨论】:

  • 我建议你看看 JavaScript API,因为你想在地图上显示结果。 code.google.com/apis/maps/documentation/javascript/basics.html有地理编码的例子。
  • 你没有提到你需要什么样的地图,但你可能会发现静态地图更容易使用:code.google.com/apis/maps/documentation/staticmaps。您只需要几个基本工具:cURL 和 SimpleXML。
  • 不幸的是,我要显示动态地图(用户键入地址,如“blabla, New York, NY”,它会显示带有缩放选项等的地图。我真的需要为此使用外部脚本吗? ? ;s

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


【解决方案1】:

您需要使用 Google Geocode API 对您的地址进行反向地理编码以获得坐标,然后该坐标可用于在地图上显示结果。例如,对于我的地址,我发布到地址参数,如下面的 url 中给出的

http://maps.googleapis.com/maps/api/geocode/json?address=154+Metro+Central+Heights+London+UK&sensor=true

可以从生成的 JSON 中获取坐标,如下所示

"geometry": {
      "location": {
        "lat": 51.5001524,
        "lng": -0.1262362
      }

获取 JSON 的 PHP 代码

<?php

$address = $_GET['address'];
$address=str_replace(" ","+",$address);
if ($address) {
    $json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$address.
    '&sensor=true');
    echo $json;
}

?>

可以在here 找到 Javascript。下面给出了解析 JSON 的关键代码

$.getJSON("getjson.php?address="+address,
        function(data){
            lat=data.results[0].geometry.location.lat;
            lng=data.results[0].geometry.location.lng;
                        //.... more map initialization code
                 }
);

我已经为您之前的问题here 设置了一个工作示例,它应该可以帮助您了解如何在地图上生成标记。如果您需要进一步说明,请告诉我。

【讨论】:

  • 好的,但是如果我需要使用 XML 而不是 JSON 怎么办?此时我输入“maps.googleapis.com/maps/api/geocode/json?”任何地方 Opera 弹出下载窗口并询问在哪里下载这个“json”文件...
  • 每个浏览器都有不同的方式来处理不同的文件格式。如果您打算查看 JSON 格式,请尝试在 firefox 或 chrome 中打开它。如果您需要 XML,则需要将 json 替换为 xml,例如 http://maps.googleapis.com/maps/api/geocode/xml?address=your+address&amp;sensor=true。我向您展示了 json 格式,因为使用纯 javascript 或 jQuery 更容易解析它。
  • 再次请注意,在 Safari 中,XML 的呈现方式与 IE 不同。如果您需要在 Safari 中查看原始 XML 文档,则需要查看源代码。不知道 Opera 是怎样的。
  • 谢谢,但正如我之前所说,使用 xml 进行 vertyhing 工作正常,但不知道如何解析:(
  • 我在这里写了一个关于解析JSON的注释stackoverflow.com/questions/3979369/…
猜你喜欢
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 2012-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
相关资源
最近更新 更多