web-dev-qa-db-fra.com

Désactiver la fenêtre d'informations sur les points d'intérêt à l'aide de Google Maps API v3

J'ai une carte personnalisée avec une bulle d'informations et des marqueurs personnalisés. Lorsque je fais un zoom sur des points d'intérêt tels que les parcs et les universités, et lorsque je clique sur une icône, une fenêtre d'informations s'ouvre. Comment désactiver la fenêtre d'information?

Mon code est le suivant:

var geocoder;
var map;
var infoBubble;
var dropdown = "";
var gmarkers = [];

var hostel_icon = new google.maps.MarkerImage('/resources/hostel_blue_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));

var bar_icon = new google.maps.MarkerImage('/resources/bar_red_icon.png',
new google.maps.Size(28,32),
new google.maps.Point(0,0),
new google.maps.Point(14,32));

var icon_shadow = new google.maps.MarkerImage('/resources/myicon_shadow.png',
new google.maps.Size(45,32),
new google.maps.Point(0,0),
new google.maps.Point(12,32));

var customIcons = {
    hostel: {
        icon: hostel_icon,
        shadow: icon_shadow
    },
    bar: {
        icon: bar_icon,
        shadow: icon_shadow
    }
};

function initialize() {
    var latlng = new google.maps.LatLng(12.82364, 26.29987);
    var myMapOptions = {
        zoom: 2,
        center: latlng,
        panControl: false,
        scaleControl: true,
        mapTypeId: google.maps.MapTypeId.TERRAIN,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR},
        navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT}
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);

    infoBubble = new InfoBubble({
        shadowStyle: 0,
        padding: 0,
        backgroundColor: 'rgb(57,57,57)',
        borderRadius: 5,
        arrowSize: 10,
        borderWidth: 1,
        maxWidth: 400,
        borderColor: '#2c2c2c',
        disableAutoPan: false,
        hideCloseButton: true,
        arrowPosition: 50,
        backgroundClassName: 'phoney',
        arrowStyle: 0
    });

    // Change this depending on the name of your PHP file
    downloadUrl("phpsqlajax_genxml_2.php", function(data) {
        var xml = parseXml(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
            var bar_name = markers[i].getAttribute("bar_name");
            var hostel_name = markers[i].getAttribute("hostel_name");
            var street = markers[i].getAttribute("street");
            var city = markers[i].getAttribute("city");
            var postcode = markers[i].getAttribute("postcode");
            var country = markers[i].getAttribute("country");
            var page = markers[i].getAttribute("page");
            var map_photo = markers[i].getAttribute("map_photo");
            var type = markers[i].getAttribute("type");
            var category = markers[i].getAttribute("category");
            var point = new google.maps.LatLng(
            parseFloat(markers[i].getAttribute("lat")),
            parseFloat(markers[i].getAttribute("lng")));

            var html = '<div class="infowindow"><div class="iwPhoto" style="width: 105px; height: 65px;">' + "<a href='" + page + "'><img src='" + map_photo + "' alt=''/></a>" + '</div><div class="iwName" style="height: 24px;">' + "<a href='" + page + "'>" + hostel_name + "</a>" + '</div><div class="iwCategory" style="height: 15px;">' + category + '</div><div class="iwCity" style="height: 29px;">' + "<a href='" + page + "'>" + city + "</a>" + '<div class="iwArrow" style="width: 29px; height: 29px;">' + "<a href='" + page + "'><img src='/resources/arrow.png'/></a>" + '</div></div></div>';

            var icon = customIcons[type] || {};
            var marker = new google.maps.Marker({
                map: map,
                position: point,
                icon: icon.icon,
                shadow: icon.shadow,
                title: bar_name
            });
            marker.bar_name = bar_name;
            marker.category = category;
            bindInfoBubble(marker, map, infoBubble, html, bar_name);

            gmarkers.Push(marker);

            str = '<option selected> - Select a club - </option>';
            for (j=0; j < gmarkers.length; j++){
                str += '<option value="'+gmarkers[j].bar_name+'">'+gmarkers[j].bar_name+', '+gmarkers[j].category+'</option>';
            }
            var str1 ='<form name="form_city" action=""><select style="width:150px;" id="select_city" name="select_cityUrl" onchange="handleSelected(this);">';
            var str2 ='</select></form>';
            dropdown = str1 + str + str2;
        }
        document.getElementById("dd").innerHTML = dropdown;
    });
}

function handleSelected(opt) {
    var indexNo = opt[opt.selectedIndex].index;
    google.maps.event.trigger(gmarkers[indexNo-1], "click");
}

function bindInfoBubble(marker, map, infoBubble, html) {
    google.maps.event.addListener(marker, 'click', function() {
        infoBubble.setContent(html);
        infoBubble.open(map, marker);
        google.maps.event.addListener(map, "click", function () {
            infoBubble.close();
        });
    });
}

function downloadUrl(url, callback) {
    var request = window.ActiveXObject ?
                  new ActiveXObject('Microsoft.XMLHTTP') :
                  new XMLHttpRequest;

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request.responseText, request.status);
        }
    };

    request.open('GET', url, true);
    request.send(null);
}

function parseXml(str) {
    if (window.ActiveXObject) {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
    } else if (window.DOMParser) {
        return (new DOMParser).parseFromString(str, 'text/xml');
    }
}

function doNothing() {}
41
Brendon

UPDATE API Google Maps JavaScript V3

Vous pouvez définir clickableIcons sur false dans MapOptions. Cela conservera les icônes de POI mais désactivera les infowindows comme vous le souhaitez.

function initialize() {
    var myMapOptions = { clickableIcons: false }
}

Plus de détails ici ...

https://developers.google.com/maps/documentation/javascript/3.exp/reference#MapOptions

52
Gavin

Voir les autres réponses pour le cliquable: fausse réponse.

Cependant, si vous voulez que soit cliquable, mais pas infowindow, appelez stop() sur la event pour empêcher l'affichage de l'infowindow, mais obtenez tout de même les informations sur l'emplacement:

map.addListener('click', function (event) {
  // If the event is a POI
  if (event.placeId) {

    // Call event.stop() on the event to prevent the default info window from showing.
    event.stop();

    // do any other stuff you want to do
    console.log('You clicked on place:' + event.placeId + ', location: ' + event.latLng);
  }
}

Pour plus d'informations, voir la documentation .


Autre option: supprimer complètement les icônes de POI, et pas seulement la fenêtre d'information:

var mapOptions = {
  styles: [{ featureType: "poi", elementType: "labels", stylers: [{ visibility: "off" }]}]
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
26
Arjan

Vous pouvez le faire en créant une carte de style sans étiquettes pour les points d'intérêt. Ceci conserve la topographie et d’autres informations intéressantes sur la carte, mais supprime les balises. 

  var remove_poi = [
    {
      "featureType": "poi",
      "elementType": "labels",
      "stylers": [
        { "visibility": "off" }
      ]
    }
  ]

map.setOptions({styles: remove_poi})
13
Farid

Vous pouvez envisager l’approche suivante pour désactiver la fenêtre d’informations de POI:

function disablePOIInfoWindow(){
    var fnSet = google.maps.InfoWindow.prototype.set;
    google.maps.InfoWindow.prototype.set = function () {
    };
}

Exemple

function initMap() {
    var latlng = new google.maps.LatLng(40.713638, -74.005529);
    var myOptions = {
        zoom: 17,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    disablePOIInfoWindow();  
}

function disablePOIInfoWindow(){
    var fnSet = google.maps.InfoWindow.prototype.set;
    google.maps.InfoWindow.prototype.set = function () {
       alert('Ok');
    };
}


google.maps.event.addDomListener(window, 'load', initMap);
html, body {
   height: 100%;
   margin: 0;
   padding: 0;
}

#map_canvas {
   height: 100%;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map_canvas"></div>

L'exemple ci-dessus concerne toutes les fenêtres d'informations. Par conséquent, si vous devez désactiver uniquement la fenêtre d'informations sur les POI, vous pouvez introduire un indicateur pour déterminer s'il s'agit ou non de la fenêtre d'informations sur les POI: 

function disablePOIInfoWindow(){
    var fnSet = google.maps.InfoWindow.prototype.set;
    google.maps.InfoWindow.prototype.set = function () {
        if(this.get('isCustomInfoWindow'))
           fnSet.apply(this, arguments);
    };
}

Exemple

function initMap() {
    var latlng = new google.maps.LatLng(40.713638, -74.005529);
    var myOptions = {
        zoom: 17,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var infowindow = new google.maps.InfoWindow({
        content: ''
    });
    infowindow.set('isCustomInfoWindow',true);
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    disablePOIInfoWindow();
    google.maps.event.addListener(map, 'click', function (event) {
        infowindow.setContent(event.latLng.lat() + "," + event.latLng.lng());
        infowindow.setPosition(event.latLng);
        infowindow.open(map, this);
    });
    
}

function disablePOIInfoWindow(){
    var fnSet = google.maps.InfoWindow.prototype.set;
    google.maps.InfoWindow.prototype.set = function () {
        if(this.get('isCustomInfoWindow'))
           fnSet.apply(this, arguments);
    };
}


//google.maps.event.addDomListener(window, 'load', initMap);
html, body {
   height: 100%;
   margin: 0;
   padding: 0;
}

#map_canvas {
   height: 100%;
}
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
            async defer></script>

9
Vadim Gremyachev

Dénommez simplement la carte pour ne pas afficher les points d’intérêt. Ceci est simple et n’enfreint pas les conditions de service de Google.

par exemple

mapOpts = {
  styles: [
    {
      featureType: "poi",
      stylers: [
         visibility: "off"
      ]
    }
  ]
};

$("#my-map").gmap(mapOpts).on("init", function(evt, map){
  // do stuff with the initialised map
});
3
Dave Sag

Nous pouvons le faire en gérant les clics sur les poi, Google api a fourni un moyen de détecter les clics sur les POI selon ce article

Basé sur l'article ci-dessus Voici une version plus simple du code qui peut être utilisée pour arrêter les clics sur les POI

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), myOptions);
    var clickHandler = new ClickEventHandler(map, Origin);
}


var ClickEventHandler = function (map, Origin) {
    this.Origin = Origin;
    this.map = map;
    this.map.addListener('click', this.handleClick.bind(this));
};

ClickEventHandler.prototype.handleClick = function (event) {
    //console.log('You clicked on: ' + event.latLng);
    if (event.placeId) {
        //console.log('You clicked on place:' + event.placeId);
        // Calling e.stop() on the event prevents the default info window from
        // showing.
        // If you call stop here when there is no placeId you will prevent some
        // other map click event handlers from receiving the event.
        event.stop();

    }
}
0
Asim Ismail

Si vous souhaitez obtenir les données sans afficher le code HTML d'InfoWindow, il vous suffit de modifier le prototype de google.maps.InfoWindow:

google.maps.InfoWindow.prototype.open = function () {
  return this; //prevent InfoWindow to appear
}
google.maps.InfoWindow.prototype.setContent = function (content) {
  if (content.querySelector) {
    var addressHTML = content.querySelector('.address');
    var address = addressHTML.innerHTML.replace(/<[^>]*>/g, ' ').trim();
    var link = content.querySelector('a').getAttribute('href');
    var payload = {
      header: 'event',
      eventName: 'place_picked',
      data: {
        name: content.querySelector('.title').innerHTML.trim(),
        address: address,
        link: link
      }
    };
    console.log('emit your event/call your function', payload);
  }
};
0
grabcode