问题
Hello this might be really silly question but I am trying to make markers disappear when they are clicked. The marker is located properly on the map but when I click it, it doesn't do anything. I was wondering why its not working. Thank you!
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var myOptions = {
center: new google.maps.LatLng(40.1, -88.2),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var myLatlng = new google.maps.LatLng(40.1, -88.2);
var temp_marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
console.log($(temp_marker));
console.log(temp_marker);
//temp_marker.click(function(){$(this).hide();});
$(temp_marker).click(function(){console.log("click is working"); $(this).hide();});
});
</script>
</head>
<body>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
回答1:
temp_marker
is a Javascript object, not a DOM element. To attach a listener to the marker (the API will handle the specifics of which DOM element to attach to and how), you should use the Google Maps API's own events system like:
google.maps.event.addListener(marker, 'click', function() {
marker.setVisible(false); // maps API hide call
});
Their documentation: Google Maps Javascript API v3 - Events
回答2:
Expanding on Ben's notes, this should go where you have declared your marker - for example:
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
google.maps.event.addListener(beachMarker, 'click', function() {
beachMarker.setVisible(false); // maps API hide call
});
}
It's taken me ages trying to figure this out. Huge credit to Ben! Thanks!
回答3:
Ben provided you with half the answer. Once you are able to detect the marker click event you need to "hide" or remove the marker from the map. The standard way for doing this with google maps is to do this:
this.setMap(null);
You can then show the map again be using setMap to assign your map object instead of null.
回答4:
marker
is a google maps object, not a DOM element. Jquery works on DOM elements.
回答5:
You can show a marker by setting the visibility true
and hide it by setting the visibility false
marker.setVisible(false); // hide the marker
回答6:
I'm not sure that you can just hide the marker, but the appropriate hook for the click event would be to do something like this when you declare marker
google.maps.event.addListener(marker, 'click', function() {
// do your hide here
});
You may have to remove the marker from the map rather than "hiding" it.
What are you trying to hide the markers for? Do you have to be able to reshow the marker? How do you plan to accomplish this?
来源:https://stackoverflow.com/questions/9594130/how-to-hide-google-maps-api-markers-with-jquery