本文介绍了如何知道哪个标记点击了GoogleMaps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript,CSS和HTML做一个包含Google Maps JavaScript API v3的小型HTML5项目。



在这个小应用程序中,我的目标是添加标记地图和每个标记点击一次,以显示有关标记的一些信息。

我的第一个方法如下:

pre $ var markersArray = [ ]。

//向地图添加一个标记并推送到数组。
函数addMarker(location){
var marker = new google.maps.Marker({
position:location,
map:map,
draggable:true,
animation:google.maps.Animation.DROP,
label:markersArray.length +,
title:markersArray.length +
});
markersArray.push(marker);
marker.addListener('click',function(){
clickMarkerEvent(markersArray.length - 1);
});
}

//监听器
函数clickMarkerEvent(index){
alert(markersArray [index] .getTitle());
}

然而,当我点击标记时,我只能得到关于最后一个标记的信息放置在地图上。听众失败。

我尝试通过在JavaScript中使用范围来纠正这种情况,而且我甚至看到了绑定,但是,这些工作都没有。



最后,我想出了完全不同的东西:

  var markersArray = []; 
var lastMarkerClicked;

函数addMarker(location){
var marker = new google.maps.Marker({
position:location,
map:map,
draggable :true,
animation:google.maps.Animation.DROP,
label:markersArray.length +,
title:markersArray.length +
});
markersArray.push(marker);
marker.addListener('click',function(){
clickMarkerEvent();
});
}

//监听器
函数clickMarkerEvent(){
lastMarkerClicked = event.target || event.srcElement;
alert(markersArray [lastMarkerClicked] .title);
}

最后一种方法的问题(即使它有效)如下:




  • 我正在访问HTML元素,而不是JavaScript元素本身使用HTML的 title 属性跟踪索引,只有标记的标题是索引(不能是其他任何东西)才能完成索引。
  • 我无法使用此处介绍的方法(),除非我做类似 markersArray [lastMarkerClicked.title] ,它指回到最后一点


总的来说,我的解决方案有效,但我真的不喜欢它。有没有更好的方法来做到这一点?



以下是我的代码,我接受建议!



 'use strict'/ *最佳实践:为了获得最佳用户体验,任何时候都只能在地图上打开一个信息窗口。多个信息窗口使地图显得杂乱无章。如果您一次只需要一个信息窗口,则只能创建一个InfoWindow对象,并在地图事件(例如用户单击)的不同位置或标记处打开它。如果你确实需要多个信息窗口,你可以同时显示多个InfoWindow对象。* / var infowindow; var contentString; var lastMarkerClicked; var markersArray = []; var map; //用markerfunction初始化map initMap (){var myLatLng = {lat:-25.363,lng:131.044}; map = new google.maps.Map(document.getElementById('map'),{zoom:4,center:myLatLng}); //当点击地图时,此事件监听器调用addMarker()。 google.maps.event.addListener(map,'click',function(event){addMarker(event.latLng);}); addMarker(myLatLng);} //向地图添加一个标记并推送到数组。 :google.maps.Animation.DROP,label:markersArray.length +,title:markersArray.length +}); markersArray.push(标记); //设置map中所有标记的映射。setMapOnAll(map){for(var i = 0; i< markersArray。 length; i ++){setMapOnMarker(i,map); (){setMapOnAll(null);} //显示当前在数组中的所有标记。function showMarkers(){setMapOnAll(map);}函数setMapOnMarker(markerIndex,map){markersArray [markerIndex] .setMap(map);}函数hideMarker(markerIndex){setMapOnMarker(markerIndex,null);}函数deleteMarker(markerIndex){hideMarker(markerIndex); markersArray [markerIndex] = null;} / *删除数组中的所有标记。请注意,上述方法不会删除标记。它只是从地图上移除标记。如果您希望删除标记,则应将其从地图中删除,然后将标记本身设置为空。 https://developers.google.com/maps/documentation/javascript/markers#remove*/function deleteMarkers(){clearMarkers(); for(var i = 0; i< markersArray.length; i ++){markersArray [i] = null; } markersArray = [];} //侦听器函数clickMarkerEvent(){lastMarkerClicked = event.target || event.srcElement;如果(markersArray [lastMarkerClicked.title] .getAnimation()!== null){markersArray [lastMarkerClicked.title] .setAnimation(null); } else {markersArray [lastMarkerClicked.title] .setAnimation(google.maps.Animation.BOUNCE); } contentString ='< div id =content>'+'< div id =siteNotice>'+'< / div>'+'< h1 id =firstHeadingclass =firstHeading >标记信息< / h1>'+'< div id =bodyContent>'+'< b> Locatoin:< / b> < p> + markersArray [lastMarkerClicked.title] .getPosition()+'< / p>'+'< b>标题:< / b> < p> + lastMarkerClicked.title +'< / p>'+'< button onclick =hideMarkerClickEvent()>隐藏标记< / button>'+'< button onclick =deleteMarkerClickEvent() >删除标记< /按钮>'+'< / div>'+'< / div>'; if(infowindow!== null&& typeof infowindow!=='undefined')infowindow.close(); infowindow = new google.maps.InfoWindow({content:contentString,maxWidth:200}); infowindow.open(map,markersArray [lastMarkerClicked.title]);} function deleteMarkerClickEvent(){deleteMarker(lastMarkerClicked.title);} function hideMarkerClickEvent(){hideMarker(lastMarkerClicked.title);}  
html,body {height:100%;保证金:0; padding:0;}#map {height:100%;} <!DOCTYPE html>< html>< head> < meta name =viewportcontent =initial-scale = 1.0,user-scalable = no> < meta charset =utf-8> < title>简单标记< / title> < link rel =stylesheettype =text / csshref =style.css>< / head>< body> < div id =map>< / div> < script type =text / javascriptsrc =markers.js>< / script> < script async defer src =https://maps.googleapis.com/maps/api/js?key=AIzaSyCGj-Dsa4PtrJiyATE_upQgOkfEkjFXqoQ&callback=initMap> < / script>< / html>

您的第一种方法几乎可以,问题是在点击侦听器被调用时,所有标记都已经在 markersArray so markersArray.length - 1 总是指向最后一个标记。只需在 addMarker 函数的作用域内创建一个变量,该变量的值保存标记的id。这里是工作代码(注意使用var index = markersArray.length; ):

 'use strict'var infowindow; var contentString; var markersArray = []; var map; //用标记函数初始化地图initMap(){var myLatLng = {lat:-25.363,lng:131.044}; map = new google.maps.Map(document.getElementById('map'),{zoom:4,center:myLatLng}); //当点击地图时,此事件监听器调用addMarker()。 google.maps.event.addListener(map,'click',function(event){addMarker(event.latLng);}); addMarker(myLatLng);} //向地图添加一个标记并推送到array.function addMarker(location){var index = markersArray.length; var marker = new google.maps.Marker({position:location,map:map,draggable:true,animation:google.maps.Animation.DROP,label:index +,title:index +}); markersArray.push(标记); //设置map中所有标记的映射setMapOnAll(map){for(var i = 0; i< markersArray()); .length; i ++){setMapOnMarker(i,map); (){setMapOnAll(null);} //显示当前在数组中的所有标记。function showMarkers(){setMapOnAll(map);}函数setMapOnMarker(markerIndex,map){markersArray [markerIndex] .setMap(map);}函数hideMarker(markerIndex){setMapOnMarker(markerIndex,null);}函数deleteMarker(markerIndex){hideMarker(markerIndex); markersArray [markerIndex] = null;} function deleteMarkers(){clearMarkers(); for(var i = 0; i< markersArray.length; i ++){markersArray [i] = null; } markersArray = [];} //监听函数clickMarkerEvent(index){if(markersArray [index] .getAnimation()!== null){markersArray [index] .setAnimation(null); } else {markersArray [index] .setAnimation(google.maps.Animation.BOUNCE); } contentString ='< div id =content>'+'< div id =siteNotice>'+'< / div>'+'< h1 id =firstHeadingclass =firstHeading >标记信息< / h1>'+'< div id =bodyContent>'+'< b> Locatoin:< / b> < p> + markersArray [index] .getPosition()+'< / p>'+'< b>标题:< / b> < p> + markersArray [index] .getTitle()+'< / p>'+'< button onclick =hideMarkerClickEvent('+ index +')>隐藏标记< / button>'+' < button onclick =deleteMarkerClickEvent('+ index +')>删除标记< / button>'+'< / div>'+'< / div>; if(infowindow!== null&& typeof infowindow!=='undefined')infowindow.close(); infowindow = new google.maps.InfoWindow({content:contentString,maxWidth:200}); infowindow.open(map,markersArray [index]);} function deleteMarkerClickEvent(index){deleteMarker(index);} function hideMarkerClickEvent(index){hideMarker(index);}  
html,body {height:100%;保证金:0; padding:0;}#map {height:100%;} <!DOCTYPE html>< html>< head> < meta name =viewportcontent =initial-scale = 1.0,user-scalable = no> < meta charset =utf-8> < title>简单标记< / title> < link rel =stylesheettype =text / csshref =style.css>< / head>< body> < div id =map>< / div> < script type =text / javascriptsrc =markers.js>< / script> < script async defer src =https://maps.googleapis.com/maps/api/js?key=AIzaSyCGj-Dsa4PtrJiyATE_upQgOkfEkjFXqoQ&callback=initMap> < / script>< / body>< / html>

I am doing a small HTML5 project with Google Maps JavaScript API v3 using JavaScript, CSS and HTML.

In this small app, my objective is to add markers to the map, and once each marker is clicked, to show some information about the marker.

My first approach was the following:

var markersArray = [];

// Adds a marker to the map and push to the array.
function addMarker(location) {
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP,
        label: markersArray.length + "",
        title: markersArray.length + ""
    });
    markersArray.push(marker);
    marker.addListener('click', function() {
        clickMarkerEvent(markersArray.length - 1);
    });
}

//listener
function clickMarkerEvent(index) {
    alert(markersArray[index].getTitle());
}

However, When I click the marker, I only get information about the last marker placed on the map. The Listener is failing.

I tried correcting this by using scopes in JavaScript, and I even gave a look at binding, however, none of those worked.

In the end, I came up with something completely different:

var markersArray = [];
var lastMarkerClicked;

function addMarker(location) {
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP,
        label: markersArray.length + "",
        title: markersArray.length + ""
    });
    markersArray.push(marker);
    marker.addListener('click', function() {
        clickMarkerEvent();
    });
}

//listener
function clickMarkerEvent() {
    lastMarkerClicked = event.target || event.srcElement;
    alert(markersArray[lastMarkerClicked].title);
}

The problem with this last approach (even though it works) is the following:

Overall my solution works, but I truly dislike it. Is there a better way to do this?

Following is my code, I am open to suggestions !

'use strict'

/*
	Best practices: For the best user experience, only one info window should be
	open on the map at any one time. Multiple info windows make the map appear
	cluttered. If you only need one info window at a time, you can create just
	one InfoWindow object and open it at different locations or markers upon map
	events, such as user clicks. If you do need more than one info window, you
	can display multiple InfoWindow objects at the same time.
*/
var infowindow;
var contentString;

var lastMarkerClicked;
var markersArray = [];

var map;

//	Initializes the map with a marker
function initMap() {

	var myLatLng = {
		lat: -25.363,
		lng: 131.044
	};

	map = new google.maps.Map(document.getElementById('map'), {
		zoom: 4,
		center: myLatLng
	});

	// This event listener calls addMarker() when the map is clicked.
	google.maps.event.addListener(map, 'click', function(event) {
		addMarker(event.latLng);
	});

	addMarker(myLatLng);
}

// Adds a marker to the map and push to the array.
function addMarker(location) {
	var marker = new google.maps.Marker({
		position: location,
		map: map,
		draggable: true,
		animation: google.maps.Animation.DROP,
		label: markersArray.length + "",
		title: markersArray.length + ""
	});
	markersArray.push(marker);
	marker.addListener('click', function() {
		clickMarkerEvent();
	});
}

// Sets the map on all markers in the array.
function setMapOnAll(map) {
	for (var i = 0; i < markersArray.length; i++) {
		setMapOnMarker(i, map);
	}
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
	setMapOnAll(null);
}

// Shows any markers currently in the array.
function showMarkers() {
	setMapOnAll(map);
}

function setMapOnMarker(markerIndex, map) {
	markersArray[markerIndex].setMap(map);
}

function hideMarker(markerIndex) {
	setMapOnMarker(markerIndex, null);
}

function deleteMarker(markerIndex) {
	hideMarker(markerIndex);
	markersArray[markerIndex] = null;
}

/*
	Deletes all markers in the array by removing references to them.
	Note that the above method does not delete the marker. It simply removes the
	marker from the map. If instead you wish to delete the marker, you should remove
	it from the map, and then set the marker itself to null.
	https://developers.google.com/maps/documentation/javascript/markers#remove
*/
function deleteMarkers() {
	clearMarkers();

	for (var i = 0; i < markersArray.length; i++) {
		markersArray[i] = null;
	}

	markersArray = [];
}

//listeners
function clickMarkerEvent() {

	lastMarkerClicked = event.target || event.srcElement;

	if (markersArray[lastMarkerClicked.title].getAnimation() !== null) {
		markersArray[lastMarkerClicked.title].setAnimation(null);
	}
	else {
		markersArray[lastMarkerClicked.title].setAnimation(google.maps.Animation.BOUNCE);
	}

	contentString = '<div id="content">' +
	'<div id="siteNotice">' +
	'</div>' +
	'<h1 id="firstHeading" class="firstHeading">Marker Info</h1>' +
	'<div id="bodyContent">' +
	'<b>Locatoin:</b> <p>' + markersArray[lastMarkerClicked.title].getPosition() + '</p>' +
	'<b>Title: </b> <p>' + lastMarkerClicked.title + '</p>' +
	'<button onclick="hideMarkerClickEvent()">Hide Marker</button>' +
	'<button onclick="deleteMarkerClickEvent()">Delete Marker</button>' +
	'</div>' +
	'</div>';

	if(infowindow !== null && typeof infowindow !== 'undefined')
		infowindow.close();

	infowindow = new google.maps.InfoWindow({
		content: contentString,
		maxWidth: 200
	});
	infowindow.open(map, markersArray[lastMarkerClicked.title]);
}

function deleteMarkerClickEvent() {
	deleteMarker(lastMarkerClicked.title);
}

function hideMarkerClickEvent() {
	hideMarker(lastMarkerClicked.title);
}
html,
body {
	height: 100%;
	margin: 0;
	padding: 0;
}

#map {
	height: 100%;
}
<!DOCTYPE html>
<html>

<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
	<meta charset="utf-8">
	<title>Simple markers</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
	<div id="map"></div>
	<script type="text/javascript" src="markers.js"></script>
	<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGj-Dsa4PtrJiyATE_upQgOkfEkjFXqoQ&callback=initMap">
	</script>
</body>

</html>

解决方案

Your first approach was almost ok, the problem was that at the point when click listener was called, all markers were already in markersArray so markersArray.length - 1 always pointed to the last marker. Just create a variable which value holds the id of the marker inside the scope of the addMarker function. Here is the working code (notice the use of var index = markersArray.length;):

'use strict'


var infowindow;
var contentString;

var markersArray = [];

var map;

//	Initializes the map with a marker
function initMap() {

	var myLatLng = {
		lat: -25.363,
		lng: 131.044
	};

	map = new google.maps.Map(document.getElementById('map'), {
		zoom: 4,
		center: myLatLng
	});

	// This event listener calls addMarker() when the map is clicked.
	google.maps.event.addListener(map, 'click', function(event) {
		addMarker(event.latLng);
	});

	addMarker(myLatLng);
}

// Adds a marker to the map and push to the array.
function addMarker(location) {
    var index = markersArray.length;
	var marker = new google.maps.Marker({
		position: location,
		map: map,
		draggable: true,
		animation: google.maps.Animation.DROP,
		label: index + "",
		title: index + ""
	});
	markersArray.push(marker);
	marker.addListener('click', function() {
		clickMarkerEvent(index);
	});
}

// Sets the map on all markers in the array.
function setMapOnAll(map) {
	for (var i = 0; i < markersArray.length; i++) {
		setMapOnMarker(i, map);
	}
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
	setMapOnAll(null);
}

// Shows any markers currently in the array.
function showMarkers() {
	setMapOnAll(map);
}

function setMapOnMarker(markerIndex, map) {
	markersArray[markerIndex].setMap(map);
}

function hideMarker(markerIndex) {
	setMapOnMarker(markerIndex, null);
}

function deleteMarker(markerIndex) {
	hideMarker(markerIndex);
	markersArray[markerIndex] = null;
}


function deleteMarkers() {
	clearMarkers();

	for (var i = 0; i < markersArray.length; i++) {
		markersArray[i] = null;
	}

	markersArray = [];
}

//listeners
function clickMarkerEvent(index) {

	if (markersArray[index].getAnimation() !== null) {
		markersArray[index].setAnimation(null);
	}
	else {
		markersArray[index].setAnimation(google.maps.Animation.BOUNCE);
	}

	contentString = '<div id="content">' +
	'<div id="siteNotice">' +
	'</div>' +
	'<h1 id="firstHeading" class="firstHeading">Marker Info</h1>' +
	'<div id="bodyContent">' +
	'<b>Locatoin:</b> <p>' + markersArray[index].getPosition() + '</p>' +
	'<b>Title: </b> <p>' + markersArray[index].getTitle() + '</p>' +
	'<button onclick="hideMarkerClickEvent(' + index + ')">Hide Marker</button>' +
	'<button onclick="deleteMarkerClickEvent(' + index + ')">Delete Marker</button>' +
	'</div>' +
	'</div>';

	if(infowindow !== null && typeof infowindow !== 'undefined')
		infowindow.close();

	infowindow = new google.maps.InfoWindow({
		content: contentString,
		maxWidth: 200
	});
	infowindow.open(map, markersArray[index]);
}

function deleteMarkerClickEvent(index) {
	deleteMarker(index);
}

function hideMarkerClickEvent(index) {
	hideMarker(index);
}
html,
body {
	height: 100%;
	margin: 0;
	padding: 0;
}

#map {
	height: 100%;
}
<!DOCTYPE html>
<html>

<head>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
	<meta charset="utf-8">
	<title>Simple markers</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
	<div id="map"></div>
	<script type="text/javascript" src="markers.js"></script>
	<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGj-Dsa4PtrJiyATE_upQgOkfEkjFXqoQ&callback=initMap">
	</script>
</body>

</html>

这篇关于如何知道哪个标记点击了GoogleMaps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:26