我找到了用Google API将地址转换为GPS经度/纬度的类。
我可以打印所有的数组:print_r($geo->adress(my address)
.
显示
Array
(
[0] => stdClass Object
(
[location] => stdClass Object
(
[lat] => 53.1243946
[lng] => 18.001958
)
[city] => Bydgoszcz
[street] => MarszaĹka Focha
[number] => 4
[code] => 85-070
)
)
但是我不能打印单个元素。我需要添加位置-> lat/lng到变量,但我不能将对象转换为字符串。我该怎么做呢?
$lat = implode(",", $geo->adress('Focha 4, Bydgoszcz'); // doesn't work at all.
<?php
echo "<pre>";
$geo = new GeoGoogle;
print_r($geo->adress('Focha 4, Bydgoszcz'));
echo"</pre>";
final class GeoGoogle {
// zwróć listę lokacji pasujących do podanego adresu
function adress($adress) {
return $this->parse(
$this->prepare(
'http://maps.googleapis.com/maps/api/geocode/json?address='
.urlencode($adress)
.'&sensor=false'
)
);
}
// zwróć listę lokacji pasujących do podanej długości i szerokości
function latlng($lat,$lng) {
return $this->parse(
$this->prepare(
'http://maps.googleapis.com/maps/api/geocode/json?latlng='
.$lat .','. $lng
.'&sensor=false'
)
);
}
/* pomocnicze */
private function prepare($uri) {
return json_decode( file_get_contents($uri) );
}
private function parse($data) {
if($data->status == 'OK') {
$results = array();
foreach($data->results as $res) { // przetwórz wyniki
$result = array(
'location' => null,
'city' => null,
'street' => null,
'number' => null,
'code' => null
);
// pobierz współrzędne
if(isset($res->geometry)) {
if(isset($res->geometry->location)) {
$result['location'] = $res->geometry->location;
}
}
// pobierz dane
foreach($res->address_components as $component) {
foreach($component->types as $type) {
switch($type) {
case 'street_number':
$result['number'] = $component->long_name;
break;
case 'route':
$result['street'] = $component->long_name;
break;
case 'postal_code':
$result['code'] = $component->long_name;
break;
case 'sublocality':
$result['city'] = $component->long_name;
break;
case 'administrative_area_level_3':
if(is_null($result['city'])) {
$result['city'] = $component->long_name;
}
break;
}
}
}
if(!is_null($result['city'])) {
$results[] = (object) $result;
}
}
return $results;
}
return array();
}
}
要从对象中获取' late '和'lng'值,请尝试:
$lat = $object->location['lat'];
$lng = $object->location['lng'];
<<p> 看到演示/strong> 编辑:仔细看看你的数据,这可能更有帮助:
$lat = $geo[0]->location['lat'];
$lng = $geo[0]->location['lng'];
参见演示2
编辑:关于Cannot use object of type GeoGoogle as array
注释中的错误
试试这个:
$my_geo = $geo->adress(my address);
$lat = $my_geo[0]->location->lat;
$lng = $my_geo[0]->location->lng;