如何在 javascript 谷歌地图上添加多个标记?
Posted
技术标签:
【中文标题】如何在 javascript 谷歌地图上添加多个标记?【英文标题】:How to add Multiple markers on javascript google maps? 【发布时间】:2021-07-22 14:15:09 【问题描述】:您好,我正在尝试在我的应用程序上添加标记,但我仍然无法在我的地图上查看标记,这是我的代码:
TS:
loadMap()
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
// alert('hi');
// let latLng = new google.maps.LatLng(13.08784, 80.27847);
let mapOptions =
center: new google.maps.LatLng(-33.92, 151.25),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++)
marker = new google.maps.Marker(
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: this.map
);
google.maps.event.addListener(marker, 'click', (function(marker, i)
return function()
infowindow.setContent(locations[i][0]);
infowindow.open(Map, marker);
)(marker, i));
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
如何查看我的 Google 地图上的标记?有什么帮助吗?
【问题讨论】:
您在创建之前尝试使用this.map
。查看 javascript 控制台并弄清楚这一点有多难?
我看不到您在地图上实际添加标记的位置。我希望像 marker.setMap(map); 这样的电话
@MikeOne 代码看起来是正确的,除了我在之前的评论中提到的。无需使用setMap
。
@MrUpsidown 我将其声明为 Map 但我仍然无法获得标记
@guru,是的,你有,但是在你使用它之后。在创建标记时,您使用的是map: this.map
,但之后您要声明this.map = new google.maps.Map(...)
。
【参考方案1】:
看cmets...
function loadMap()
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
let mapOptions =
center: new google.maps.LatLng(-33.92, 151.25),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
// Moved this line up here
this.map = new google.maps.Map(document.getElementById('map'), mapOptions); // changed the "native element" to a standard DOM element for the sake of this example
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++)
marker = new google.maps.Marker(
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: this.map // You are using this.map here so it needs to be created before
);
google.maps.event.addListener(marker, 'click', (function(marker, i)
return function()
infowindow.setContent(locations[i][0]);
infowindow.open(Map, marker);
)(marker, i));
loadMap();
#map
height: 180px;
<div id="map"></div>
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
【讨论】:
以上是关于如何在 javascript 谷歌地图上添加多个标记?的主要内容,如果未能解决你的问题,请参考以下文章