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

3

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

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

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

但是我的页面一直报错:

引用错误: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>

请注意,我的php.ini中有allow_url_fopen = On


我认为你在JavaScript部分使用了PHP函数。 - Sutulustus
展示一下生成的URL是什么样子。 - gawi
请将您的解决方案发布为答案并接受它。 - geocodezip
2个回答

11

问题已解决,出现问题的是<script>标签内的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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接