Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 768
Wordpressor Avatar asked Sep 03 '13 15:09

Wordpressor


People also ask

How do I change my address with latitude and longitude?

To get the latitude of the address in cell B2, use the formula = GetLatitude(B2) To get the longitude of the address in cell B2, use the formula = GetLongitude(B2) To get both the latitude and longitude of the address in cell B2, use the formula = GetCoordinates(B2)

Is Google geocoding free?

The Geocoding API uses a pay-as-you-go pricing model. Geocoding API requests generate calls to one of two SKUs depending on the type of request: basic or advanced.


1 Answers

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:

  • http://www.fcsoftware.co.uk/blog/?p=66
  • https://developers.google.com/maps/documentation/geocoding
like image 196
Neil Robertson Avatar answered Oct 02 '22 01:10

Neil Robertson