NiviJah
NiviJah

Reputation: 179

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.

Upvotes: 3

Views: 12764

Answers (2)

Kamran Ahmed
Kamran Ahmed

Reputation: 12438

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

Upvotes: 1

NiviJah
NiviJah

Reputation: 179

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;
?>

Upvotes: 11

Related Questions