我目前正在使用以下方法从GoogleMaps中获取坐标。我能把这个写得更短/更高效吗?
2013年6月21日版
到目前为止,旧的谷歌地理编码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);
}
您可以使用json而不是xml。json是更新的、轻量级的和面向对象的。
我建议您使用http_build_query(),而不是尝试使用Regex构建SearchQuery。还有其他字符需要转义。
这是一个相当长的方法。也许有一个只处理与GoogleMaps通信的Class是有意义的(Class GeoBackend,方法为getGeoDataForAddress(),它返回一个GeoData对象,可以请求Corinates等)