谷歌地图 API - 按地址添加标记 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46868703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google maps API - add marker by address javascript
提问by Aviv Eyal
I have database of places with addresses and I want to add markers on google maps.
我有带地址的地点数据库,我想在谷歌地图上添加标记。
It shows only the default marker, seems like the geocoder.geocode() does nothing. For an example I'm trying to add a marker on " New York City", with no success.
它只显示默认标记,似乎 geocoder.geocode() 什么也不做。例如,我试图在“纽约市”上添加一个标记,但没有成功。
<script>
var geocoder;
var map;
var address = "new york city";
geocoder = new google.maps.Geocoder();
function initMap() {
var uluru = { lat: -25.363, lng: 131.044 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
codeAddress(address);
}
function codeAddress(address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == 'OK') {
var marker = new google.maps.Marker({
position: address,
map: map
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap"
async defer></script>
回答by rafon
The reason why you are not getting the expected result is because there is incorrect codes placement in the example you provided. You are trying to get a new instance of Google Maps API Geocoder before Google Maps is fully loaded. Hence, Google Maps API Geocoder will not work because of this Uncaught ReferenceError: google is not defined. You should get a new instance of Google Maps API Geocoder inside the initMap() function.
您未获得预期结果的原因是您提供的示例中的代码位置不正确。您正在尝试在 Google Maps 完全加载之前获取 Google Maps API Geocoder 的新实例。因此,由于此Uncaught ReferenceError: google is not defined,Google Maps API Geocoder 将无法工作。您应该在 initMap() 函数中获得一个新的 Google Maps API Geocoder 实例。
You can check Maps JavaScript API Geocoding to learn more.
您可以查看Maps JavaScript API 地理编码 以了解更多信息。
You can also check Best Practices When Geocoding Addresses.
您还可以查看对地址进行地理编码时的最佳实践。
Please also note that you should not include your API_KEY when posting Google Maps APi related questions.
另请注意,在发布与 Google Maps API 相关的问题时,您不应包含 API_KEY。
Here's the whole code:
这是整个代码:
<!DOCTYPE html>
<html>
<head>
<title>Geocoding service</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var geocoder;
var map;
var address = "new york city";
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
geocoder = new google.maps.Geocoder();
codeAddress(geocoder, map);
}
function codeAddress(geocoder, map) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === '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);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
Live demo here.
现场演示在这里。
Hope it helps!
希望能帮助到你!
回答by SphynxTech
There were several errors in your code. Normally, it should looks OK now:
您的代码中有几个错误。通常,它现在看起来应该没问题:
var geocoder;
var map;
var address = "new york city";
function initMap() {
geocoder = new google.maps.Geocoder();
var uluru = { lat: -25.363, lng: 131.044 };
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
codeAddress(address);
}
function codeAddress(address) {
geocoder.geocode({ 'address': address }, function (results, status) {
console.log(results);
var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
console.log (latLng);
if (status == 'OK') {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
console.log (map);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
This is a list of your errors:
这是您的错误列表:
- You have to initialize your geocode when the google maps api is fully loaded. It means that you have to put this line of code:
geocoder = new google.maps.Geocoder();in theinitMap (). - When you initialize the map you have to refer to a global variable. In your code, you create a new variable map in your function. But, you have to pass by the global's variable map.
- When, you want to get the position of the geocoder's result, you have to pass by this line of code:
results[0].geometry.location.lat ().
- 当 google maps api 完全加载时,您必须初始化您的地理编码。这意味着你必须把这行代码:
geocoder = new google.maps.Geocoder();在initMap (). - 当您初始化地图时,您必须引用一个全局变量。在您的代码中,您在函数中创建了一个新的变量映射。但是,您必须通过全局变量映射。
- 当您想获得地理编码器结果的位置时,您必须通过以下代码行:
results[0].geometry.location.lat ().
You may refer to the documentation.
你可以参考文档。
Tell me if you have some questions.
如果您有任何问题,请告诉我。

