web-dev-qa-db-fra.com

Comment afficher plusieurs Google Maps par page avec API V3

J'ai le script suivant. Et je veux que les deux cartes apparaissent sur la page, mais peu importe ce que j'essaie, je ne peux obtenir que la première carte initialize () à afficher ... pas la deuxième. Aucune suggestion? (aussi, je ne peux pas l'ajouter dans le code, mais la première carte est affichée dans <div id="map_canvas"></div><div id="route"></div> Merci!

<script type="text/javascript"> 
// Create a directions object and register a map and DIV to hold the 
// resulting computed directions

var map;
var directionsPanel;
var directions;

function initialize() {
  map = new GMap(document.getElementById("map_canvas"));
  map.setCenter(new GLatLng(41.1255275,-73.6964801), 15);
  directionsPanel = document.getElementById("route");
  directions = new GDirections(map, directionsPanel);
  directions.load("from: Armonk Fire Department, Armonk NY to: <?php echo $LastCallGoogleAddress;?> ");

  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
}

</script> 


<div id="map_canvas2" style="width:200px; height:200px;"></div>
<div id="route2"></div>

<script type="text/javascript"> 
// Create a directions object and register a map and DIV to hold the 
// resulting computed directions

var map2;
var directionsPanel2;
var directions2;

function initialize2() {
  map2 = new GMap(document.getElementById("map_canvas2"));
  map2.setCenter(new GLatLng(41.1255275,-73.6964801), 15);
  directionsPanel2 = document.getElementById("route2");
  directions2 = new GDirections(map2, directionsPanel2);
  directions2.load("from: ADDRESS1 to: ADDRESS2 ");

  map2.addControl(new GSmallMapControl());
  map2.addControl(new GMapTypeControl());
}

</script> 

<script type="text/javascript">
function loadmaps(){
    initialize();
    initialize2();  
}
</script>
47
Bill

Voici comment j'ai pu générer plusieurs cartes sur la même page en utilisant Google Map API V3. Veuillez noter qu’il s’agit d’un code caché qui répond au problème ci-dessus.

Le bit HTML

<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;"></div>
<div id="map_canvas2" style="width:700px; height:500px; margin-left:80px;"></div>

Javascript pour l'initialisation de la carte

<script type="text/javascript">
var map, map2;

function initialize(condition) {
    // create the maps
    var myOptions = {
        zoom: 14,
        center: new google.maps.LatLng(0.0, 0.0),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
}
</script> 
67
Philar

Je viens de terminer l'ajout de Google Maps à l'offre de CMS de mon entreprise. Mon code autorise plus d'une carte dans une page.

Notes:

  • J'utilise jQuery
  • Je mets l'adresse dans le contenu, puis je l'analyse pour générer dynamiquement la carte.
  • J'inclus un marqueur et une fenêtre d'information dans ma carte

HTML:

<div class="block maps first">
    <div class="content">
        <div class="map_canvas">
            <div class="infotext">
                <div class="location">Middle East Bakery & Grocery</div>
                <div class="address">327 5th St</div>
                <div class="city">West Palm Beach</div>
                <div class="state">FL</div>
                <div class="Zip">33401-3995</div>
                <div class="country">USA</div>
                <div class="phone">(561) 659-4050</div>
                <div class="zoom">14</div>
            </div>
        </div>
    </div>
</div>
<div class="block maps last">
    <div class="content">
        <div class="map_canvas">
            <div class="infotext">
                <div class="location">Global Design, Inc</div>
                <div class="address">3434 SW Ash Pl</div>
                <div class="city">Palm City</div>
                <div class="state">FL</div>
                <div class="Zip">34990</div>
                <div class="country">USA</div>
                <div class="phone"></div>
                <div class="zoom">17</div>
            </div>
        </div>
    </div>
</div>

Code:

$(document).ready(function() {
    $maps = $('.block.maps .content .map_canvas');
    $maps.each(function(index, Element) {
        $infotext = $(Element).children('.infotext');

        var myOptions = {
            'zoom': parseInt($infotext.children('.zoom').text()),
            'mapTypeId': google.maps.MapTypeId.ROADMAP
        };
        var map;
        var geocoder;
        var marker;
        var infowindow;
        var address = $infotext.children('.address').text() + ', '
                + $infotext.children('.city').text() + ', '
                + $infotext.children('.state').text() + ' '
                + $infotext.children('.Zip').text() + ', '
                + $infotext.children('.country').text()
        ;
        var content = '<strong>' + $infotext.children('.location').text() + '</strong><br />'
                + $infotext.children('.address').text() + '<br />'
                + $infotext.children('.city').text() + ', '
                + $infotext.children('.state').text() + ' '
                + $infotext.children('.Zip').text()
        ;
        if (0 < $infotext.children('.phone').text().length) {
            content += '<br />' + $infotext.children('.phone').text();
        }

        geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                myOptions.center = results[0].geometry.location;
                map = new google.maps.Map(Element, myOptions);
                marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: $infotext.children('.location').text()
                });
                infowindow = new google.maps.InfoWindow({'content': content});
                google.maps.event.addListener(map, 'tilesloaded', function(event) {
                    infowindow.open(map, marker);
                });
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.open(map, marker);
                });
            } else {
                alert('The address could not be found for the following reason: ' + status);
            }
        });
    });
});
13
Sonny

Voici un autre exemple si vous avez le long et le lat, dans mon cas, en utilisant le package de type de données de carte Google Umbraco et en générant une liste de div avec la classe "map", par exemple.

<div class="map" id="UK">52.21454000000001,0.14044490000003407,13</div>

mon JavaScript en utilisant Google Maps API v3 basé sur exemples Cultiv Razor

$('.map').each(function (index, Element) {
    var coords = $(Element).text().split(",");
    if (coords.length != 3) {
        $(this).display = "none";
        return;
    }
    var latlng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
    var myOptions = {
        zoom: parseFloat(coords[2]),
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: false,
        mapTypeControl: true,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
        }
    };
    var map = new google.maps.Map(Element, myOptions);

    var marker = new google.maps.Marker({
        position: latlng,
        map: map
    });
});
7
Justin Moore

OP souhaitait deux cartes spécifiques, mais si vous souhaitez avoir un nombre dynamique de cartes sur une page (par exemple, une liste des détaillants), vous devez suivre un autre chemin. L'implémentation standard de l'API Google Maps définit la carte comme une variable globale, cela ne fonctionnera pas avec un nombre dynamique de cartes. Voici mon code pour résoudre ceci sans variables globales:

function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var mapOptions = {
            zoom: 14,
            center: results[0].geometry.location,
            disableDefaultUI: true
        };
        var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
    } else {
        alert("Geocode was not successful for the following reason: " + status);
    }
});
}

Il suffit de transmettre l’ID et l’adresse de chaque carte à la fonction pour tracer la carte et marquer l’adresse.

7
Daniel Hedenström

Tiré de ces exemples - guide , implémentation .

  1. définissez votre <div> avec le id approprié
  2. inclure les options de Google Map avec foundation appelant.
  3. inclure foundation et rem js lib.

Exemple -

index.html -

<div class="row">
   <div class="large-6 medium-6 ">
      <div id="map_canvas" class="google-maps">
      </div>
   </div>
   <br>
   <div class="large-6 medium-6 ">
      <div id="map_canvas_2" class="google-maps"></div>
   </div>
</div>
<script src="/js/foundation.js"></script>
<script src="/js/google_maps_options.js"></script>
<script src="/js/rem.js"></script>
<script>
   jQuery(function(){
       setTimeout(initializeGoogleMap,700);
   });
</script>

google_maps_options.js -

function initializeGoogleMap()
{
    $(document).foundation();
    var latlng = new google.maps.LatLng(28.561287,-81.444465);
    var latlng2 = new google.maps.LatLng(28.507561,-81.482359);

    var myOptions =
    {
        zoom: 13,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var myOptions2 =
    {
        zoom: 13,
        center: latlng2,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };


    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var map2 = new google.maps.Map(document.getElementById("map_canvas_2"), myOptions2);


    var myMarker = new google.maps.Marker(
    {
        position: latlng,
        map: map,
        title:"Barnett Park"
   });

    var myMarker2 = new google.maps.Marker(
    {
        position: latlng2,
        map: map2,
        title:"Bill Fredrick Park at Turkey Lake"
    });


}
5
URL87

Je devais charger un nombre dynamique de cartes Google, avec des emplacements dynamiques. Alors j'ai fini avec quelque chose comme ça. J'espère que ça aide. J'ajoute LatLng en tant qu'attribut de données sur la carte div.

Donc, créez simplement des divs avec la classe "maps". Chaque carte peut ensuite avoir différents identifiants et latLng comme celui-ci. Bien sûr, vous pouvez configurer divers attributs de données pour le zoom, etc.

Le code est peut-être plus propre, mais cela fonctionne assez bien pour moi.

<div id="map123" class="maps" data-gps="46.1461154,17.1580882"></div>
<div id="map456" class="maps" data-gps="45.1461154,13.1080882"></div>

  <script>
      var map;
      function initialize() {
        // Get all map canvas with ".maps" and store them to a variable.
        var maps = document.getElementsByClassName("maps");

        var ids, gps, mapId = '';

        // Loop: Explore all elements with ".maps" and create a new Google Map object for them
        for(var i=0; i<maps.length; i++) {

          // Get ID of single div
          mapId = document.getElementById(maps[i].id);

          // Get LatLng stored in data attribute. 
          // !!! Make sure there is no space in data-attribute !!!
          // !!! and the values are separated with comma !!!
          gps = mapId.getAttribute('data-gps');

          // Convert LatLng to an array
          gps = gps.split(",");

          // Create new Google Map object for single canvas 
          map = new google.maps.Map(mapId, {
            zoom: 15,
            // Use our LatLng array bellow
            center: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
            mapTypeId: 'roadmap',
            mapTypeControl: true,
            zoomControlOptions: {
                position: google.maps.ControlPosition.RIGHT_TOP
            }
          });

          // Create new Google Marker object for new map
          var marker = new google.maps.Marker({
            // Use our LatLng array bellow
            position: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
            map: map
          });
        }
      }
  </script>
4
fvrab

Vous n'avez pas défini de div avec id = "map_canvas", vous n'avez que id = "map_canvas2" et id = "route2". Les identifiants div doivent correspondre à l'argument du constructeur GMap ().

2
mattmoon9

Vous pouvez essayer nex approche css

 .map {
            height: 300px;
            width: 100%;
        }

HTML

@foreach(var map in maps)
{
  <div id="[email protected]" lat="@map.Latitude" lng="@map.Longitude" class="map">
  </div>
}

JavaScript

 <script>
    var maps = [];
    var markers = [];
    function initMap() {
        var $maps = $('.map');
        $.each($maps, function (i, value) {
            var uluru = { lat: parseFloat($(value).attr('lat')), lng: parseFloat($(value).attr('lng')) };

            var mapDivId = $(value).attr('id');

            maps[mapDivId] = new google.maps.Map(document.getElementById(mapDivId), {
                zoom: 17,
                center: uluru
            });

            markers[mapDivId] = new google.maps.Marker({
                position: uluru,
                map: maps[mapDivId]
            });
        })
    }
</script>

<script async defer
        src="https://maps.googleapis.com/maps/api/js?language=ru-Ru&key=YOUR_KEY&callback=initMap">
</script>
1
Anton Valintsev
var maps_qty;
for (var i = 1; i <= maps_qty; i++)
    {
        $(".append_container").append('<div class="col-lg-10 grid_container_'+ (i) +'" >' + '<div id="googleMap'+ i +'" style="height:300px;"></div>'+'</div>');
        map = document.getElementById('googleMap' + i);
        initialize(map,i);
    }

// Intialize Google Map with Polyline Feature in it.

function initialize(map,i)
    {
        map_index = i-1;
        path_lat_long = [];
        var mapOptions = {
            zoom: 2,
            center: new google.maps.LatLng(51.508742,-0.120850)
        };

        var polyOptions = {
            strokeColor: '#000000',
            strokeOpacity: 1.0,
            strokeWeight: 3
        };

        //Push element(google map) in an array of google maps
        map_array.Push(new google.maps.Map(map, mapOptions));
        //For Mapping polylines to MUltiple Google Maps
        polyline_array.Push(new google.maps.Polyline(polyOptions));
        polyline_array[map_index].setMap(map_array[map_index]);
    }

// For Resizing Maps Multiple Maps.

google.maps.event.addListener(map, "idle", function()
    {
      google.maps.event.trigger(map, 'resize');
    });

map.setZoom( map.getZoom() - 1 );
map.setZoom( map.getZoom() + 1 );
0
Divyanshu Rawat

J'avais un problème particulier: j'avais une application à page unique et devais afficher différentes cartes, dans différents divs, une à chaque fois. Je l'ai résolu d'une manière pas très belle mais d'une manière fonctionnelle. Au lieu de masquer les éléments DOM avec la propriété display, j'ai utilisé la propriété visibilité pour le faire. Avec cette approche, Google Maps API n’a aucun mal à connaître les dimensions des divs où j’ai instancié les cartes.

0
Afonso Praça