Get Latitude and Longitude from address in php

Get latitude and longitude co-ordinates from a given address using google map api. This process is sometimes called Geocoding. Geocoding is the process of converting addresses into geographic coordinates (Latitude and Longitude).

This can be done either using XML or JSON api. Both methods are given here.

Using XML

 <?php
  $address = 'Cannaught Place, New Delhi, India';
  
  $url = 'http://maps.googleapis.com/maps/api/geocode/xml?address='.
          urlencode($address).'&sensor=true';
  $xml = simplexml_load_file($url);
  
  $status = $xml->status;
  
  if($status=="OK"){
      $latitude = $xml->result[0]->geometry->location->lat;
      $longitude = $xml->result[0]->geometry->location->lng;
      echo 'Latitude = '.$latitude;
      echo '<br>';
      echo 'Longitude = '.$longitude;
  }else{
      echo "Invalid Address !!";
  }
 ?>


Using JSON

 <?php
  $address = 'Cannaught Place, New Delhi, India';
  
  $url  = 'http://maps.googleapis.com/maps/api/geocode/json?address='.
           urlencode($address).'&sensor=true';
  $json = @file_get_contents($url);
  $data = json_decode($json);
  
  $status = $data->status;
  
  if($status=="OK"){
      $latitude = $data->results[0]->geometry->location->lat;
      $longitude = $data->results[0]->geometry->location->lng;
      echo 'Latitude = '.$latitude;
      echo '<br>';
      echo 'Longitude = '.$longitude;
  }else{
      echo "Invalid Address !!";
  }
 ?>

If you want a reverse process like getting address from given latitude and longitude coordinates. You can Visit this post.
Get Latitude and Longitude from address in php Get Latitude and Longitude from address in php Reviewed by JS Pixels on September 26, 2012 Rating: 5

2 comments:

Altaf Web. Powered by Blogger.