web-dev-qa-db-fra.com

Mappage de plusieurs emplacements avec Google Maps JavaScript API v3 et Geocoding API

J'utilise Google Maps JavaScript API v3 pour générer une carte comportant plusieurs emplacements/marqueurs. Je n'ai que l'adresse de ces emplacements, pas les coordonnées. J'utilise donc l'API de géocodage pour obtenir les coordonnées.

J'ai enfin réussi à faire fonctionner le géocodage de Google, alors les marqueurs d'emplacement apparaissent là où ils sont censés être. Cependant, le même contenu apparaît dans chaque InfoWindow. Il semble que je ne puisse pas passer les tableaux de localisation dans la fonction de géocodage. (Incidemment, j'ai également essayé de créer une variable pour les résultats du géocode et de déplacer la fonction infoWindow outside de la fonction de géocode, mais je ne pouvais pas que cela fonctionne.)

J'ai déjà essayé cent façons différentes. J'espère que quelqu'un verra ce que je n'ai pas pu voir.

    var locations = [
        ['Location 1 Name', 'Location 1 Address', 'Location 1 URL'],
        ['Location 2 Name', 'Location 2 Address', 'Location 2 URL'],
        ['Location 3 Name', 'Location 3 Address', 'Location 3 URL']
    ];

    geocoder = new google.maps.Geocoder();

    for (i = 0; i < locations.length; i++) {

        title = locations[i][0];
        address = locations[i][1];
        url = locations[i][2];

        geocoder.geocode({ 'address' : locations[i][1] }, function(results, status) {
          marker = new google.maps.Marker({
              icon: 'marker_blue.png',
              map: map,
              position: results[0].geometry.location,
              title: title,
              animation: google.maps.Animation.DROP,
              address: address,
              url: url
          })
          infoWindow(marker, map, title, address, url);
        })

    }

    function infoWindow(marker, map, title, address, url) {
        google.maps.event.addListener(marker, 'click', function() {
            var html = "<div><h3>" + title + "</h3><p>" + address + "<br></div><a href='" + url + "'>View location</a></p></div>";
            iw = new google.maps.InfoWindow({ content : html, maxWidth : 350});
            iw.open(map,marker);
        });
    }
4
lacoder

Il s’agit d’un doublon de adresses multiples de la fenêtre d’informations cartographiques de Google via xml , mais il ne s’agit pas d’un doublon exact. Le géocodeur est asynchrone. Ainsi, lorsque le rappel du géocodeur est exécuté, la valeur de l'adresse correspond à celle de la fin de la boucle pour tous les appels.

La réponse est la même: la solution la plus simple consiste à utiliser la fonction de fermeture de la fonction pour associer l'appel du géocodeur au résultat renvoyé:

function geocodeAddress(locations, i) {
    var title = locations[i][0];
    var address = locations[i][1];
    var url = locations[i][2];
    geocoder.geocode({
        'address': locations[i][1]
    },

    function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({
                icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
                map: map,
                position: results[0].geometry.location,
                title: title,
                animation: google.maps.Animation.DROP,
                address: address,
                url: url
            })
            infoWindow(marker, map, title, address, url);
            bounds.extend(marker.getPosition());
            map.fitBounds(bounds);
        } else {
            alert("geocode of " + address + " failed:" + status);
        }
    });
}

Violon de travail

extrait de code:

var locations = [
  ['Location 1 Name', 'New York, NY', 'Location 1 URL'],
  ['Location 2 Name', 'Newark, NJ', 'Location 2 URL'],
  ['Location 3 Name', 'Philadelphia, PA', 'Location 3 URL']
];

var geocoder;
var map;
var bounds = new google.maps.LatLngBounds();

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  geocoder = new google.maps.Geocoder();

  for (i = 0; i < locations.length; i++) {


    geocodeAddress(locations, i);
  }
}
google.maps.event.addDomListener(window, "load", initialize);

function geocodeAddress(locations, i) {
  var title = locations[i][0];
  var address = locations[i][1];
  var url = locations[i][2];
  geocoder.geocode({
      'address': locations[i][1]
    },

    function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({
          icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
          map: map,
          position: results[0].geometry.location,
          title: title,
          animation: google.maps.Animation.DROP,
          address: address,
          url: url
        })
        infoWindow(marker, map, title, address, url);
        bounds.extend(marker.getPosition());
        map.fitBounds(bounds);
      } else {
        alert("geocode of " + address + " failed:" + status);
      }
    });
}

function infoWindow(marker, map, title, address, url) {
  google.maps.event.addListener(marker, 'click', function() {
    var html = "<div><h3>" + title + "</h3><p>" + address + "<br></div><a href='" + url + "'>View location</a></p></div>";
    iw = new google.maps.InfoWindow({
      content: html,
      maxWidth: 350
    });
    iw.open(map, marker);
  });
}

function createMarker(results) {
  var marker = new google.maps.Marker({
    icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
    map: map,
    position: results[0].geometry.location,
    title: title,
    animation: google.maps.Animation.DROP,
    address: address,
    url: url
  })
  bounds.extend(marker.getPosition());
  map.fitBounds(bounds);
  infoWindow(marker, map, title, address, url);
  return marker;
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

19
geocodezip

Étape 1

Vous devez d’abord créer un emplacement de carte correspondant à l’emplacement où vous souhaitez ajouter cette carte sur votre application Web. Commencez donc par créer une page JSP/HTML/ASP dans laquelle vous devez créer un emplacement pour afficher la carte.

<div id="map_canvas" style="width: 1350px; height: 500px"></div>

Étape 2

Ci-dessous, j'écris le script à l'aide duquel vous pouvez voir la carte sur votre application Web.

<script src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=TRUEORFALSE"></script>
<script type="text/javascript">
var map;
var markers;
function initialize() {

    $
            .ajax({

                type : "POST",
                url : "Your Servlet Name", //Servlet Name
                data : $("#FormID"),

                success : function(responseJson) {


                    var result = $.parseJSON(responseJson);
                    markers = result;

                    // Below mapOptions var includes styling maps and zoom level of your map, it also includes mapTypeId.
                    var mapOptions = {
                        center : new google.maps.LatLng(
                                markers[0].latitude, markers[0].longitude),
                        zoom : 5,
                        scrollwheel: false, 
                        styles : [ {
                            "featureType" : "administrative",
                            "elementType" : "labels.text.fill",
                            "stylers" : [ {
                             "color" : "#444444"
                            } ]
                           }, {
                            "featureType" : "landscape",
                            "elementType" : "all",
                            "stylers" : [ {
                             "color" : "#f2f2f2"
                            } ]
                           }, {
                            "featureType" : "poi",
                            "elementType" : "all",
                            "stylers" : [ {
                             "visibility" : "off"
                            } ]
                           }, {
                            "featureType" : "poi.park",
                            "elementType" : "geometry.fill",
                            "stylers" : [ {
                             "visibility" : "on"
                            }, {
                             "color" : "#1ba093"
                            } ]
                           }, {
                            "featureType" : "road",
                            "elementType" : "all",
                            "stylers" : [ {
                             "saturation" : -100
                            }, {
                             "lightness" : 45
                            } ]
                           }, {
                            "featureType" : "road.highway",
                            "elementType" : "all",
                            "stylers" : [ {
                             "visibility" : "simplified"
                            } ]
                           }, {
                            "featureType" : "road.arterial",
                            "elementType" : "labels.icon",
                            "stylers" : [ {
                             "visibility" : "off"
                            } ]
                           }, {
                            "featureType" : "transit",
                            "elementType" : "all",
                            "stylers" : [ {
                             "visibility" : "off"
                            } ]
                           }, {
                            "featureType" : "water",
                            "elementType" : "all",
                            "stylers" : [ {
                             "color" : "#00748c"
                            }, {
                             "visibility" : "on"
                            } ]
                           } ],
                        mapTypeId : google.maps.MapTypeId.ROADMAP
                    };
                    map = new google.maps.Map(document
                            .getElementById("map_canvas"), mapOptions);
                    addYourLocationButton(map,marker);  
                    //Create and open InfoWindow.
                    var infoWindow = new google.maps.InfoWindow();                      

                    for (var i = 0; i < markers.length; i++) {
                        var data = markers[i];

                        var myLatlng = new google.maps.LatLng(
                                data.latitude, data.longitude);
                        var marker = new google.maps.Marker({
                            position : myLatlng,
                            animation: google.maps.Animation.DROP,
                            map : map,
                            title : //Any title that you want to display while cursor over the marker.
                        });

                        //Click event 
                        (function(marker, data) {
                            google.maps.event
                                    .addListener(
                                            marker,
                                            "click",
                                            function(e) {                                                   
                                                infoWindow
                                                        .setContent("<div style = 'width:300px;min-height:50px'>+Write information about your location if you want.+"</div>");
                                                infoWindow
                                                        .open(map, marker);
                                            });
                        })(marker, data);

                    }

                }

            });

}

1
Preet Soni