Skip to content

Instantly share code, notes, and snippets.

@clnmcgrw
Last active November 25, 2021 11:16
Show Gist options
  • Save clnmcgrw/9086505 to your computer and use it in GitHub Desktop.
Save clnmcgrw/9086505 to your computer and use it in GitHub Desktop.
Google Maps API Geocode Example - PHP/JSON
<?php
// address to map
$map_address = "";
$url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=".urlencode($map_address);
$lat_long = get_object_vars(json_decode(file_get_contents($url)));
// pick out what we need (lat,lng)
$lat_long = $lat_long['results'][0]->geometry->location->lat . "," . $lat_long['results'][0]->geometry->location->lng;
?>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map_canvas"></div>
<script>
(function() {
function initialize() {
var myLatlng = new google.maps.LatLng(<?php echo $lat_long; ?>),
mapOptions = {
zoom: 15,
center: myLatlng
},
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: '<?php echo $map_address; ?>'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
})();
</script>
@skladany
Copy link

Thanks for this! A few tips for anyone using this bit of code:

  • Make sure you have a defined height/width on the #map_canvas, or else you won't see the map at all
  • While this bit of code doesn't require an API key, you are rate-limited by your IP address to about 2,500 queries. Therefore you would't want to use this on a live site, but you could use this to geocode addresses then store them locally. (ie, you should only need to geocode once-per-address)

@pawebgate
Copy link

Thanks a lot, with a small modification i made it working

@enklenke
Copy link

Thank you very much!!!!!!! its perfect for me.

@Yao228
Copy link

Yao228 commented May 2, 2017

A lot of thanks , your script work very good.

@rami1973
Copy link

how to use geocode in url

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment