Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting google maps geocode from address

I'm trying to get the latitude and longitude from an address with a Google maps JSON request and display a map on a page.

The URL that is being created from my request works fine, and creates a valid URL with JSON info:

http://maps.google.com/maps/api/geocode/json?address=<?php echo $_GET['q'];?>&sensor=false

But I keep getting an error on my page:

ReferenceError: file_get_contents is not defined

And nothing is being displayed. Here is the full HTML and JS code:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&language=iw"></script>
<script>
$geocode=file_get_contents("http://maps.google.com/maps/api/geocode/json?address=<?php echo     $_GET['q'];?>&sensor=false");

$output= json_decode($geocode);

$lat = $output.results[0].geometry.location.lat();
$lng = $output.results[0].geometry.location.lng();

var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(32.069373, 32.069373), // numbers are here for testing
mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas"></div>

Note that allow_url_fopen = On is in my php.ini.

like image 823
NiviJah Avatar asked Aug 31 '26 14:08

NiviJah


2 Answers

Solved, the problem was with php code inside script tags. I changed the first part to this:

<?php 
$geocode=file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".$_GET['q']."&sensor=false");

$output= json_decode($geocode);

$lat = $output->results[0]->geometry->location->lat;
$lng = $output->results[0]->geometry->location->lng;
?>
like image 56
NiviJah Avatar answered Sep 03 '26 04:09

NiviJah


Although I am a little late to the party, but here is a Geocoding library that I wrote on top of Google's Geocoding API that let's you get alot of things out of the address

http://github.com/hugobots/php-geocode

like image 34
Kamran Ahmed Avatar answered Sep 03 '26 04:09

Kamran Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!