简体   繁体   中英

unable to hide two dimensional marker array in Google API 3

  My marker  is at the end   

I am unable to hide the marker using setMap, Error in Console Please help!

Thanks in advance

 markers[i][j].setMap(null); markers.setMap(null); var markers = [ ['office', 'Albania', 42.158410, 19.940845], ['production plant', 'Albania', 40.198905, 20.039722], ['R&D service', 'Albania', 41.090835, 19.545337], ['office', 'Algeria', 28.164666, 3.160335] ]; `Uncaught TypeError: markers[i][j].setMap`

You can't hide a marker based on the elements in your array. They don't have .setMap methods. The markers need to be google.maps.Marker objects. When you create the markers, keep references to them in another array (say "gmarkers"), then use that to hide/show them.

proof of concept fiddle (using your data)

 var markers = [ ['office', 'Albania', 42.158410, 19.940845], ['production plant', 'Albania', 40.198905, 20.039722], ['R&D service', 'Albania', 41.090835, 19.545337], ['office', 'Algeria', 28.164666, 3.160335] ]; var map; var gmarkers = []; function toggleMarker() { var markerId = parseInt(document.getElementById('markerid').value); if (gmarkers[markerId].getMap() == null) { gmarkers[markerId].setMap(map); } else { gmarkers[markerId].setMap(null); } } function initialize() { map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: new google.maps.LatLng(-33.92, 151.25), mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i; var bounds = new google.maps.LatLngBounds(); for (i = 0; i < markers.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(markers[i][2], markers[i][3]), map: map }); bounds.extend(marker.getPosition()); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(markers[i][0]); infowindow.open(map, marker); } })(marker, i)); gmarkers.push(marker); } map.fitBounds(bounds); } google.maps.event.addDomListener(window, 'load', initialize);
 html, body, #map { height: 100%; margin: 0px; padding: 0px }
 <script src="https://maps.googleapis.com/maps/api/js"></script> <input type="text" id="markerid" value="2" /> <input type="button" onclick="toggleMarker()" value="toggle" /> <div id="map"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM