我目前使用以下方法从GoogleMaps获取坐标。 我可以写这个更短/更高效吗?从GoogleMaps获取地理坐标有没有更简单/更简单的方法?
EDIT 2013年6月21日
截至目前老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);
}
+1是的,今天我看到了JSON支持,当我切换到新的API。我认为老一代不支持它,我想我会继续这样做。 – insertusernamehere 2013-06-21 09:55:44