我使用以下代码将地址转换为经度和纬度。代码取自http://www.phpmoot.com/php-get-latitudelongitude-from-an-address-with-google-map/
$address = '201 S. Division St., Ann Arbor, MI 48104'; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
echo $address.'<br>Lat: '.$lat.'<br>Long: '.$long;
这在我以前的主机上工作得很好,但是当我将网站移动到TSO主机时,它不再工作。这其中可能有什么原因呢?
我试过在url和服务器api密钥中使用浏览器api密钥,这也不起作用。这样的
http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key=****API_KEY_GOES_HERE****&sensor=false
欢迎任何帮助。TSO主机支持似乎无法解决
只是为了确保它是服务器相关的,我会建议你尝试使用页面中的JS。请尝试实现下面的代码与更改您的div ID和密钥。同时传递地址变量到相关的地方。
<script>
function initialize() {
var center;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': $AdressYouGotFromThePost}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mycenter = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());//
var mapProp = {
center:mycenter,
zoom:11
};
var map=new google.maps.Map(document.getElementById("YOURDIVID"),mapProp);
var request = {
location: mycenter,
radius: '20000',
types: ['bar,night_club,cafe,museum,movie_theater,zoo,aquapark']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createPhotoMarker(results[i]);
}
}
}
function createPhotoMarker(place) {
var photos = place.photos;
if (!photos) {
return;
}
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name
//icon: photos[0].getUrl({'maxWidth': 55, 'maxHeight': 55})
});
//console.log(photos[0].getUrl({'maxWidth': 105, 'maxHeight': 105}));
var contenthtml = "<p>"+place.name+"</p><img src="+photos[0].getUrl({'maxWidth': 105, 'maxHeight': 105})+" width='105px'/>";
var infowindow = new google.maps.InfoWindow({
content:contenthtml
});
google.maps.event.addListener(marker,'click',function() {
map.setZoom(17);
map.setCenter(marker.getPosition());
infowindow.open(map,marker);
});
}
});
}
</script>
<script async="" defer="" src="https://maps.googleapis.com/maps/api/js?key=YOURACCESSKEYHERE&callback=initialize&libraries=places">
使用php方法将地址转换为经纬度,如下例http://www.phpmoot.com/php-get-latitudelongitude-from-an-address-with-google-map/
导致在TSO主机共享云服务器上达到api限制。使用API密钥似乎没有任何区别。解决方案是不使用php方法,而是使用Javascript方法,按照谷歌的例子在这里- https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple