Подтвердить что ты не робот

Как отобразить несколько карт Google на странице с API V3

У меня есть следующий script. И я хочу, чтобы обе карты отображались на странице, но независимо от того, что я пытаюсь, я могу получить только первую инициализацию карты() для отображения... вторая - нет. Какие-либо предложения? (также, я не могу добавить его в код, но первая карта отображается в <div id="map_canvas"></div><div id="route"></div> Спасибо!

<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>
4b9b3361

Ответ 1

Вот как я смог создать несколько карт на одной странице с помощью Google Map API V3. Пожалуйста, обратите внимание, что это код манжеты, который устраняет проблему выше.

Бит 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 для инициализации карты

<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> 

Ответ 2

Я только что закончил добавлять Карты Google в предложение моей компании CMS. Мой код позволяет отображать более одной карты на странице.

Примечания:

  • Я использую jQuery
  • Я помещаю адрес в контент и затем разбираю его, чтобы динамически генерировать карту.
  • Я включаю маркер и InfoWindow на моей карте.

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>

Код:

$(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);
            }
        });
    });
});

Ответ 3

Вот еще один пример, если у вас есть long и lat, в моем случае с использованием пакета Umbraco Google Map Datatype и вывода списка div с классом "map", например.

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

мой JavaScript с помощью API Карт Google v3 на основе Примеры 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
    });
});

Ответ 4

OP потребовалось две конкретные карты, но если вы хотите иметь динамическое количество карт на одной странице (например, список мест розничной торговли), вам нужно пройти еще один маршрут. Стандартная реализация API карт Google определяет карту как глобальную переменную, это не будет работать с динамическим числом карт. Здесь мой код для решения этого без глобальных переменных:

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);
    }
});
}

Просто передайте идентификатор и адрес каждой карты функции для построения карты и отметьте адрес.

Ответ 5

Взятые из этих примеров - руководство, реализация.

  • установите <div> с помощью id
  • включают опции Google Map с вызовом foundation.
  • включить foundation и rem js lib.

Пример -

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"
    });


}

Ответ 6

Вы не определили div с id = "map_canvas", у вас есть только id = "map_canvas2" и id = "route2". Идентификаторы div должны соответствовать аргументу в конструкторе GMap().

Ответ 7

Вы можете попробовать nex-подход 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>

Ответ 8

У меня была одна особенная проблема: у меня было одностраничное приложение, и мне приходилось показывать разные карты в разных divs каждый раз. Я решил это не очень красиво, но функционально. Вместо того чтобы скрыть элементы DOM с помощью свойства display, я использовал свойство видимость, чтобы сделать это. При таком подходе API Карт Google не имел никаких проблем с тем, чтобы знать размеры разделов, в которых я создал экземпляры карт.

Ответ 9

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 );

Ответ 10

Мне нужно было загрузить динамическое число карт Google с динамическими местоположениями. Поэтому у меня получилось что-то вроде этого. Надеюсь, поможет. Я добавляю LatLng как атрибут данных на карте div.

Итак, просто создайте divs с "картами" класса. Каждый холст карты может иметь различные идентификаторы и LatLng, как это. Конечно, вы можете настроить различные атрибуты данных для масштабирования и так далее.

Возможно, код может быть более чистым, но он работает для меня довольно хорошо.

<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>

Ответ 11

Взгляните на этот комплект для Laravel, который я создал недавно!


https://github.com/Maghrooni/googlemap

это поможет вам создать одну или несколько карт на вашей странице!

вы можете найти класс на
src/googlemap.php

Pls Сначала прочитайте файл readme и не забудьте передать другой ID, если вы хотите иметь несколько карт на одной странице