web-dev-qa-db-fra.com

Ajout d'ID aux marqueurs de carte Google

J'ai un script qui boucle et ajoute des marqueurs un à la fois.

J'essaie d'obtenir que le marqueur actuel ait une fenêtre d'information et que je n'ai que 5 marqueurs sur une carte à la fois (4 sans fenêtre d'information et 1 avec)

Comment pourrais-je ajouter un identifiant à chaque marqueur pour pouvoir supprimer et fermer les fenêtres d’information au besoin?.

C'est la fonction que j'utilise pour définir le marqueur:

function codeAddress(address, contentString) {

var infowindow = new google.maps.InfoWindow({
  content: contentString
});

if (geocoder) {

  geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

        map.setCenter(results[0].geometry.location);

       var marker = new google.maps.Marker({
          map: map, 
          position: results[0].geometry.location
       });

       infowindow.open(map,marker);

      } else {
       alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

}

74
Nick

JavaScript est un langage dynamique. Vous pouvez simplement l'ajouter à l'objet lui-même.

var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};

En outre, tous les objets v3 étant étendus MVCObject() . Vous pouvez utiliser:

marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");
182
CrazyEnigma

Ajoutez simplement une autre solution qui fonctionne pour moi. Vous pouvez simplement l’ajouter aux options du marqueur:

var marker = new google.maps.Marker({
    map: map, 
    position: position,

    // Custom Attributes / Data / Key-Values
    store_id: id,
    store_address: address,
    store_type: type
});

Et puis récupérez-les avec:

marker.get('store_id');
marker.get('store_address');
marker.get('store_type');
12
zen.c

J'ai une simple classe Location que j'utilise pour gérer toutes les tâches liées aux marqueurs. Je vais coller mon code ci-dessous pour que vous puissiez jeter un coup d'œil à.

La dernière ligne est ce qui crée réellement les objets marqueurs. Il passe en revue certains JSON de mes emplacements, qui ressemblent à ceci:

{"locationID":"98","name":"Bergqvist Järn","note":null,"type":"retail","address":"Smidesvägen 3","zipcode":"69633","city":"Askersund","country":"Sverige","phone":"0583-120 35","fax":null,"email":null,"url":"www.bergqvist-jb.com","lat":"58.891079","lng":"14.917371","contact":null,"rating":"0","distance":"45.666885421019"}

Voici le code:

Si vous regardez la méthode target() dans ma classe Location, vous verrez que je garde des références aux infowindow et que je peux simplement open() et close() à cause de une référence.

Voir une démonstration en direct: http://ww1.arbesko.com/fr/locator/ (tapez dans une ville suédoise, comme Stockholm, puis appuyez sur Entrée)

var Location = function() {
    var self = this,
        args = arguments;

    self.init.apply(self, args);
};

Location.prototype = {
    init: function(location, map) {
        var self = this;

        for (f in location) { self[f] = location[f]; }

        self.map = map;
        self.id = self.locationID;

        var ratings = ['bronze', 'silver', 'gold'],
            random = Math.floor(3*Math.random());

        self.rating_class = 'blue';

        // this is the marker point
        self.point = new google.maps.LatLng(parseFloat(self.lat), parseFloat(self.lng));
        locator.bounds.extend(self.point);

        // Create the marker for placement on the map
        self.marker = new google.maps.Marker({
            position: self.point,
            title: self.name,
            icon: new google.maps.MarkerImage('/wp-content/themes/arbesko/img/locator/'+self.rating_class+'SmallMarker.png'),
            shadow: new google.maps.MarkerImage(
                                        '/wp-content/themes/arbesko/img/locator/smallMarkerShadow.png',
                                        new google.maps.Size(52, 18),
                                        new google.maps.Point(0, 0),
                                        new google.maps.Point(19, 14)
                                    )
        });

        google.maps.event.addListener(self.marker, 'click', function() {
            self.target('map');
        });

        google.maps.event.addListener(self.marker, 'mouseover', function() {
            self.sidebarItem().mouseover();
        });

        google.maps.event.addListener(self.marker, 'mouseout', function() {
            self.sidebarItem().mouseout();
        });

        var infocontent = Array(
            '<div class="locationInfo">',
                '<span class="locName br">'+self.name+'</span>',
                '<span class="locAddress br">',
                    self.address+'<br/>'+self.zipcode+' '+self.city+' '+self.country,
                '</span>',
                '<span class="locContact br">'
        );

        if (self.phone) {
            infocontent.Push('<span class="item br locPhone">'+self.phone+'</span>');
        }

        if (self.url) {
            infocontent.Push('<span class="item br locURL"><a href="http://'+self.url+'">'+self.url+'</a></span>');
        }

        if (self.email) {
            infocontent.Push('<span class="item br locEmail"><a href="mailto:'+self.email+'">Email</a></span>');
        }

        // Add in the lat/long
        infocontent.Push('</span>');

        infocontent.Push('<span class="item br locPosition"><strong>Lat:</strong> '+self.lat+'<br/><strong>Lng:</strong> '+self.lng+'</span>');

        // Create the infowindow for placement on the map, when a marker is clicked
        self.infowindow = new google.maps.InfoWindow({
            content: infocontent.join(""),
            position: self.point,
            pixelOffset: new google.maps.Size(0, -15) // Offset the infowindow by 15px to the top
        });

    },

    // Append the marker to the map
    addToMap: function() {
        var self = this;

        self.marker.setMap(self.map);
    },

    // Creates a sidebar module for the item, connected to the marker, etc..
    sidebarItem: function() {
        var self = this;

        if (self.sidebar) {
            return self.sidebar;
        }

        var li = $('<li/>').attr({ 'class': 'location', 'id': 'location-'+self.id }),
            name = $('<span/>').attr('class', 'locationName').html(self.name).appendTo(li),
            address = $('<span/>').attr('class', 'locationAddress').html(self.address+' <br/> '+self.zipcode+' '+self.city+' '+self.country).appendTo(li);

        li.addClass(self.rating_class);

        li.bind('click', function(event) {
            self.target();
        });

        self.sidebar = li;

        return li;
    },

    // This will "target" the store. Center the map and zoom on it, as well as 
    target: function(type) {
        var self = this;

        if (locator.targeted) {
            locator.targeted.infowindow.close();
        }

        locator.targeted = this;

        if (type != 'map') {
            self.map.panTo(self.point);
            self.map.setZoom(14);
        };

        // Open the infowinfow
        self.infowindow.open(self.map);
    }
};

for (var i=0; i < locations.length; i++) {
    var location = new Location(locations[i], self.map);
    self.locations.Push(location);

    // Add the sidebar item
    self.location_ul.append(location.sidebarItem());

    // Add the map!
    location.addToMap();
};
3
whalesalad

Pourquoi ne pas utiliser un cache qui stocke chaque objet marqueur et référence un ID?

var markerCache= {};
var idGen= 0;

function codeAddress(addr, contentStr){
    // create marker
    // store
    markerCache[idGen++]= marker;
}

Edit: bien sûr, cela repose sur un système d’index numérique qui n’offre pas une propriété de longueur comme un tableau. Vous pouvez bien sûr prototyper l'objet Object et créer une longueur, etc. pour une telle chose. OTOH, générer une valeur d'identifiant unique (MD5, etc.) de chaque adresse pourrait être la solution.

1
bdl