是否有更简单/更短的方式从Google地图获取地理坐标?

时间:2012-08-02 15:28:35

标签: php google-maps

我目前正在使用以下方法从GoogleMaps获取坐标。 我可以写得更短/更有效吗?

编辑21.06.2013

截至目前,旧Google Geocoding API已关闭。这是我修改过的代码,适用于最新版本。我已经更新了这篇文章,如果有人发现它并发现它有用。

public function getGeographicCoordinatesFromGoogle()
{
    // create address string
    $value = $this->address_line_1 . ' ' .
             $this->postal_code . ' ' .
             $this->city . ' ' .
             $this->country;
    $value = preg_replace('!\s+!', '+', $value);

    // create request
    $request = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' .
               $value . '&sensor=false';

    // get value from xml request
    $xml = file_get_contents($request);
    $doc = new \DOMDocument('1.0', 'UTF-8');
    @$doc->loadXML($xml);

    // fetch result
    $result = $doc->getElementsByTagName('lat')->item(0)->nodeValue . ',' .
              $doc->getElementsByTagName('lng')->item(0)->nodeValue;

    // check result
    if (!preg_match('/(-?\d+\.\d+),(-?\d+\.\d+)/', $result) ) {
        $result = null;
    }
    // assign value
    $this->setGeographicCoordinates($result);
}

2 个答案:

答案 0 :(得分:1)

您可以使用json而不是xml。 json更新,轻巧,面向对象。

答案 1 :(得分:0)

我建议您使用http_build_query()而不是尝试使用Regex构建SearchQuery。还有其他字符需要转义。

这是一个很长的方法。也许有一个只处理与GoogleMaps通信的类是有意义的(带有方法getGeoDataForAddress()的类GeoBackend,它返回一个GeoData-Object,可以请求Cordinates等。)

相关问题