Google Maps - converting address to latitude & longitude - PHP backend?

Wordpressor picture Wordpressor · Sep 3, 2013 · Viewed 45.6k times · Source

is it possible to convert (in PHP back-end):

<?php
  $Address = "Street 1, City, Country"; // just normal address
?>

to

<?php
  $LatLng = "10.0,20.0"; // latitude & lonitude
?>

The code I'm currently using is the default one:

<script type='text/javascript' src='https://maps.googleapis.com/maps/api/js?v=3.exp&#038;sensor=false'></script>

<script>

function initialize() {
  var myLatlng = new google.maps.LatLng(10.0,20.0);
  var mapOptions = {
    zoom: 16,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'This is a caption'
  });
}

google.maps.event.addDomListener(window, 'load', initialize); 

</script>

<div id="map"></div>

I've been reading https://developers.google.com/maps/documentation/geocoding for a while now but I'm not experienced enough I guess.

Thanks.

Answer

Neil Robertson picture Neil Robertson · Sep 30, 2013

This works for me:

<?php
  $Address = urlencode($Address);
  $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true";
  $xml = simplexml_load_file($request_url) or die("url not loading");
  $status = $xml->status;
  if ($status=="OK") {
      $Lat = $xml->result->geometry->location->lat;
      $Lon = $xml->result->geometry->location->lng;
      $LatLng = "$Lat,$Lon";
  }
?>

References: