2009-10-06 50 views

回答

4

使用谷歌地圖API和PHP獲取座標:

$url = 'http://maps.google.com/maps/geo?q='.$address.'&output=json&oe=utf8&sensor=false&key='.$api_key; 
$data = @file_get_contents($url); 
$jsondata = json_decode($data,true); 
if(is_array($jsondata)&& $jsondata ['Status']['code']==200){ 
    $lat = $jsondata ['Placemark'][0]['Point']['coordinates'][0]; 
    $lon = $jsondata ['Placemark'][0]['Point']['coordinates'][1]; 
} 
8

而另一種方式:

$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$address.'&sensor=false'); 

$output= json_decode($geocode); 

$lat = $output->results[0]->geometry->location->lat; 
$long = $output->results[0]->geometry->location->lng; 
3

這裏是我的類:

class GeoCoder { 
public static function getLatLng($address){ 
    try{ 
     $address = urlencode($address); 
     $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$address.'&sensor=false'); 

     $output= json_decode($geocode); 

     $lat = $output->results[0]->geometry->location->lat; 
     $lng = $output->results[0]->geometry->location->lng; 
     if(is_numeric($lat) && is_numeric($lng)){ 
      return array("lat" => $lat, "lng" => $lng); 
     } 
    } 
    catch(Exception $e){    
     return false; 
    } 
} 

}

相關問題