从地址获取谷歌地图地理编码

时间:2013-07-10 06:32:47

标签: php json google-maps

我正在尝试从包含Google地图JSON请求的地址获取经度和经度,并在页面上显示地图。

从我的请求创建的URL工作正常,并使用JSON信息创建有效的URL:

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

但我的网页上一直出现错误:

  

ReferenceError:未定义file_get_contents

没有显示任何内容。这是完整的HTML和JS代码:

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

请注意allow_url_fopen = On在我的php.ini中。

2 个答案:

答案 0 :(得分:11)

解决了,问题在于脚本标签内的php代码。我将第一部分更改为:

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

答案 1 :(得分:1)

虽然我很晚才参加聚会,但这是一个我在Google的地理编码API上编写的地理编码库让你得到很多东西超出地址

https://github.com/kamranahmedse/php-geocode

相关问题