我在使用 Google map 地理编码时遇到一些问题。
- 由于某种原因, map 可以在这里使用,但不能在我的网站上使用 - 我不明白为什么
- 如果我不包含
address =encodeURI(address);
,我会收到INVALID_REQUEST
警报。 - 如果我
警告
地址变量,我会得到未定义
- 如果我运行您在下面看到的代码,它会将 map 位置更改为堪萨斯城的某个地方。
function initMap() {
var map = new google.maps.Map(document.getElementById('google_map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
address = encodeURI(address);
alert(address);
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
#google_map{
width: 500px;
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDxaUk0vMG2pm-ISIDrbi1PzKHBj5gzxVg&callback=initMap"></script>
<div id="floating-panel">
<input id="address" type="textbox" value="4 Chantry Road, Bishops Stortford, Hertfordshire, CM23">
<input id="submit" type="button" value="Geocode">
</div>
<div id="google_map"></div>
有人可以帮忙吗?
最佳答案
我为解决这个问题所做的是:
确保启用服务 API(在 Google API 仪表板上)
生成用于 Javascript API 的 Javascript 凭据
生成用于服务器 API 的服务器凭据
为地理编码配置初始值设定项
HTML 代码
<input type="text" id="mapaddress" />
<input type="submit" id="change" onclick="changeMap()">
<div id="map" style="width: 413px; height: 300px;"></div>
JS:
function changeMap(){
var mapOptions = {
zoom: 16,
center: new google.maps.LatLng(54.00, -3.00),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var geocoder = new google.maps.Geocoder();
//var address = '3410 Taft Blvd Wichita Falls, TX 76308';
var address= document.getElementById("mapaddress").value;
if(!address) {
address = '3410 Taft Blvd Wichita Falls, TX 76308';
}
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
return false;
}
关于javascript - 谷歌地图地理编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50115904/