문제

I am using Google Maps API v3, with InfoBox, in order to style the popups that appear on clicking a marker.

Here's my InfoBox setup:

// New InfoWindow
infobox = new InfoBox({
    content: document.getElementById('marker-info'),
    disableAutoPan: false,
    pixelOffset: new google.maps.Size(-140, 0),
    zIndex: null,
    closeBoxMargin: '10px 9px 12px 0',
    closeBoxURL: siteURL + 'wp-content/themes/bmk-wp-build/img/close-google-popup.png',
    infoBoxClearance: new google.maps.Size(1, 1)
});

I have a Google Map with many markers, which is being set up with Wordpress using ACF and Locations field. All working great but the only issue is the InfoBox is outputting the same content for each marker. This is, clearly, to do with this line:

content: document.getElementById('marker-info'),

Here is my PHP/HTML:

<?php while ( $company_query->have_posts() ) : $company_query->the_post(); ?>
<?php $location = get_field('location'); if ( !empty($location) ) : ?>
    <div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>" id="<?php echo get_the_ID(); ?>">
        <div id="marker-info" class="marker-info <?php echo get_the_ID(); ?>">
            <?php echo wp_get_attachment_image(get_field('logo'), 'full'); ?>
        </div>
    </div>
<?php endif; ?>
<?php endwhile; ?>

Clearly, having an id set in the while loop is a bad idea, and stupid, so I can obviously get rid of that, but how would I change:

content: document.getElementById('marker-info'),

to get each .marker-info for each InfoBox for each marker?

도움이 되었습니까?

해결책

I worked it out with this...

google.maps.event.addListener(marker, 'click', function() {
    console.log( $marker.children().html() );

    infobox.open(map,marker);
    infobox.setContent($marker.children().html());

});

다른 팁

Why not use the same InfoBox everywhere, and declare it initially without the content option? If I understand right, you can have an event handler for each marker, and set the callback to use the one infobox. Something like the following:

var markers = document.getElementsByClassName('marker');
for( var i = 0; i < markers.length; i++ ) {
    google.maps.event.addDomListener(markers[i], 'click', function() {
         infobox.setContent(this.children[0]);
         infobox.open(map);
    });
}

With this, you can probably get rid of using the ID altogether. If you want to keep the ID, I suggest you move setting the ID inside the class name, to appending it to the actual ID inside the PHP code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top