Use Google Maps API to Get Latitude and Longitude


/ Published in: PHP
Save to your folder(s)

When creating a custom Google Map, the latitude and longitude for the place of interest are needed. Enter in the Address, City, and State, and the lat and lng pair will be returned.


Copy this code and paste it in your HTML
  1. <?php
  2. function getLatandLong($addr,$city,$state)
  3. {
  4. global $lat;
  5. global $lng;
  6.  
  7. $doc = new DOMDocument();
  8. $doc->load("http://maps.google.com/maps/api/geocode/xml?address=".$addr.",+".$city.",+".$state."&sensor=false"); //input address
  9.  
  10. //traverse the nodes to get to latitude and longitude
  11. $results = $doc->getElementsByTagName("result");
  12. $results = $results->item(0);
  13. $results = $results->getElementsByTagName("geometry");
  14. $results = $results->item(0);
  15. $results = $results->getElementsByTagName("location");
  16.  
  17. foreach($results as $result)
  18. {
  19. $lats = $result->getElementsByTagName("lat");
  20. $lat = $lats->item(0)->nodeValue;
  21.  
  22. $lngs = $result->getElementsByTagName("lng");
  23. $lng = $lngs->item(0)->nodeValue;
  24. }
  25. }
  26. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.