Я пытаюсь поместить 2 карты Google с несколькими маркерами с разными местоположениями на странице с API Карт Google V3. Я получил это далеко:Несколько Google Maps с несколькими маркерами на одной странице.
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
var map,map2,mapOptions,mapOptions2,markers,markers2,infoWindowContent,infoWindowContent2;
var bounds = new google.maps.LatLngBounds();
var bounds2 = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap',
scrollwheel: false,
styles:[
{
"stylers": [
{ "saturation": -100 }
]
}
],
};
var mapOptions2 = {
mapTypeId: 'roadmap',
scrollwheel: false,
styles:[
{
"stylers": [
{ "saturation": -100 }
]
}
],
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("google-maps"), mapOptions);
map2 = new google.maps.Map(document.getElementById("locations-google"), mapOptions2);
map.setTilt(45);
map2.setTilt(45);
// Multiple Markers
var markers = [
['TITLE HERE', 1,1],
['TITLE HERE', 1,1]
];
var markers2 = [
['TITLE HERE', 1,1],
['TITLE HERE', 1,1]
];
var infoWindowContent = [
['<div class="info_content">' +
'<h4>TITLE HERE</h4>' +
'info here' +
'</div>'],
['<div class="info_content">' +
'<h4>TITLE HERE</h4>' +
'info here' +
'</div>']
];
var infoWindowContent2 = [
['<div class="info_content">' +
'<h4>TITLE HERE</h4>' +
'info here' +
'</div>'],
['<div class="info_content">' +
'<h4>TITLE HERE</h4>' +
'info here' +
'</div>']
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
var infoWindow2 = new google.maps.InfoWindow(), marker2, i;
// Loop through our array of markers & place each one on the map
for(i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: "<?php echo get_stylesheet_directory_uri(); ?>/images/marker.png"
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
for(i = 0; i < markers2.length; i++) {
var position2 = new google.maps.LatLng(markers2[i][1], markers2[i][2]);
bounds2.extend(position2);
marker2 = new google.maps.Marker({
position: position2,
map: map2,
title: markers2[i][0],
icon: "<?php echo get_stylesheet_directory_uri(); ?>/images/marker.png"
});
// Allow each marker to have an info window
google.maps.event.addListener(marker2, 'click', (function(marker2, i) {
return function() {
infoWindow.setContent(infoWindowContent2[i][0]);
infoWindow.open(map2, marker2);
}
})(marker2, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds2);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(8);
google.maps.event.removeListener(boundsListener);
});
}
Но когда я запускаю это, первая карта будет работать нормально и показывает правильное количество мест и т.д. Но когда дело доходит до второго она не загружается и дает мне эта ошибка в консоли «Uncaught TypeError: невозможно прочитать свойство« lat »из null». Я так озадачен тем, почему он это делает, и я не могу понять это вообще.
Спасибо!
Хотя эти параметры определяются в соответствии с требованиями они могут быть опущены при вызове метода fitBounds (fitBounds будет устанавливать как центр, так и масштаб) –
Эй, это правильно. Добавление центра и уровня масштабирования фактически устранило ошибку, но я не понял, что fitBounds дважды вызывался на одном и том же объекте карты. Хороший улов. – MrUpsidown