我正在使用 Mapbox 制作 map ,它还有每个国家、州和城市的位置列表,当我单击其中一个时,应该显示它们的位置。
所以我添加了mapbox的地理编码器L.mapbox.geocoder
,但是有些地方的坐标不够精确,例如美国或法国。
我该如何解决这个问题?
我也想过使用谷歌的地理编码服务Google Geocoder 。 我怎样才能做到这一点?
希望你能帮助我。
最佳答案
如果您要使用 Mapbox,则无法保证全世界的数据准确,因为 Mapbox 街道基于一个名为 OpenStreetMap 的自愿数据库。 :“Mapbox Streets 的数据主要来自 OpenStreetMap,部分部分使用了 Natural Earth 和我们自己的调整” [source] 。因此,如果您必须更准确,Google Geocoder 应该是您选择的 API。 pricing取决于每天的请求。
这是一个谷歌地理编码示例:
<!DOCTYPE html>
<html>
<head>
<title>Geocoding service</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
</style>
</head>
<body>
<div id="floating-panel">
<input id="address" type="textbox" value="Sydney, NSW">
<input id="submit" type="button" value="Geocode">
</div>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('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;
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.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);
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap"
async defer></script>
</body>
</html>
关于javascript - 如何添加地理编码服务(对于 MapBox),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290545/