我正试图通过谷歌地图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中。
问题已经解决,问题是脚本标记中的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;
?>
虽然我在派对上迟到了一点,但这里有一个我在谷歌的Geocoding API上写的Geocodinglibrary,让你从地址中获得很多东西
http://github.com/hugobots/php-geocode