Я пытаюсь открыть маркеры Google Maps при нажатии кнопки. Я прошел через несколько веток, которые мне очень помогли, но теперь я просто получаю
(index):336 Uncaught ReferenceError: markers is not defined
at HTMLButtonElement.<anonymous> ((index):336)
at HTMLButtonElement.dispatch (jquery.js?ver=1.12.4-wp:3)
at HTMLButtonElement.r.handle (jquery.js?ver=1.12.4-wp:3)
Создание маркеров из WP ACF Repeater и нанесение на карту
<?php if( have_rows('markers', 'option') ): $idNum = 1 ?>
<div class="acf-map">
<?php while (have_rows('markers', 'option')) {
the_row();
$name = get_sub_field('name');
$desc = get_sub_field('description');
$lng = get_sub_field('longitude');
$lat = get_sub_field('latitude');
$loc = get_sub_field('location');
$id = $idNum;
$idNum = $idNum + 1;
?>
<div class="marker" data-marker-id="<?php echo $id; ?>" data-lat="<?php echo $lat; ?>" data-lng="<?php echo $lng; ?>">
<p><?php echo $name; ?></p>
<span><?php echo $desc; ?></span>
<span><?php echo $id; ?></span>
</div>
<?php if( have_rows('markers_europe', 'option') ): ?>
<?php while (have_rows('markers_europe', 'option')) {
the_row();
$name = get_sub_field('name');
$desc = get_sub_field('description');
$lng = get_sub_field('longitude');
$lat = get_sub_field('latitude');
$loc = get_sub_field('location');
$id = $idNum;
$idNum = $idNum + 1;
?>
<div class="marker" data-marker-id="<?php echo $id; ?>" data-lat="<?php echo $lat; ?>" data-lng="<?php echo $lng; ?>">
<p><?php echo $name; ?></p>
<span><?php echo $desc; ?></span>
<span><?php echo $id; ?></span>
</div>
</div>
<?php endif; ?>
Код Google Maps
(function( $ ) {
/**
* initMap
*
* Renders a Google Map onto the selected jQuery element
*
* @date 22/10/19
* @since 5.8.6
*
* @param jQuery $el The jQuery element.
* @return object The map instance.
*/
function initMap( $el ) {
// Find marker elements within map.
var $markers = $el.find('.marker');
// Create gerenic map.
var mapArgs = {
zoom : 6,
mapTypeId : google.maps.MapTypeId.ROADMAP,
styles : mapStyle
};
var map = new google.maps.Map( $el[0], mapArgs );
// Add markers.
map.markers = [];
$markers.each(function(){
initMarker( $(this), map );
});
// Center map based on markers.
centerMap( map );
// Return map instance.
return map;
}
/**
* initMarker
*
* Creates a marker for the given jQuery element and map.
*
* @date 22/10/19
* @since 5.8.6
*
* @param jQuery $el The jQuery element.
* @param object The map instance.
* @return object The marker instance.
*/
function initMarker( $marker, map ) {
// Get position from marker.
var lat = $marker.data('lat');
var lng = $marker.data('lng');
var latLng = {
lat: parseFloat( lat ),
lng: parseFloat( lng )
};
var icon = {
url: '<?php echo get_template_directory_uri(); ?>/img/map-marker.svg',
anchor: new google.maps.Point(0,0),
scaledSize: new google.maps.Size( 17, 17 ) , // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point( 8.5, 8.5 ) // anchor
}
// Create marker instance.
var marker = new google.maps.Marker({
position : latLng,
optimized: false,
map: map,
flat: true,
visible: true,
icon:icon,
title: "I might be here",
selectionUsedID: $marker.data('marker-id')
});
// Append to reference for later use.
map.markers.push( marker );
$('#fakeClick').on('click', function () {
google.maps.event.trigger(markers[$(this).data('marker-id')], 'click');
});
// If marker contains HTML, add it to an infoWindow.
if( $marker.html() ){
// Create info window.
var infowindow = new google.maps.InfoWindow({
content: $marker.html()
});
// Show info window when marker is clicked.
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
console.log(marker.selectionUsedID);
});
}
}
/**
* centerMap
*
* Centers the map showing all markers in view.
*
* @date 22/10/19
* @since 5.8.6
*
* @param object The map instance.
* @return void
*/
function centerMap( map ) {
// Create map boundaries from all map markers.
var bounds = new google.maps.LatLngBounds();
map.markers.forEach(function( marker ){
bounds.extend({
lat: marker.position.lat(),
lng: marker.position.lng()
});
});
// Case: Single marker.
if( map.markers.length == 1 ){
map.setCenter( bounds.getCenter() );
// Case: Multiple markers.
} else{
map.fitBounds( bounds );
}
}
Особо важная часть, пока только тестируем с помощью одной кнопки, но расширимся несколькими кнопками с data-marker-id
, чтобы связать кнопку и соответствующий маркер. Я использую пользовательские данные selectionUsedID
, заполненные из data-marker-id
в маркере, для связи с переменной $id
в маркере, заполненном из ACF.
$('#fakeClick').on('click', function () {
google.maps.event.trigger(markers[$(this).data('marker-id')], 'click');
});
Извинения за стену кода, но я подумал, что в случаях Uncaught ReferenceError детали важнее, чем краткость.
Заранее спасибо!