简体   繁体   中英

Adding multiple markers to a map

I am trying to Lopo through PHP records and use the coordinates to populate markers on a leaflet map.

I however am getting an error in the console:

Error: Invalid LatLng object: (18.473396, undefined)

Php:

           <?php foreach($positions as $position):
                    $longitude = get_field( 'longitude', 'category_' . $position->term_id . '' );
                    $latitude = get_field( 'latitude', 'category_' . $position->term_id . '' );
            ?>
               <div class="marker" data-lat="<?php echo $latitude; ?>" data-lng="<?php echo $longitude; ?>"></div>
           <?php endforeach; ?>

The html output for the above is:

<div class="marker" data-lat="33.985571" data-lng="18.470870"></div>
<div class="marker" data-lat="33.994995" data-lng="18.473396"></div>

The JS

$(document).ready(function() {
    var map = L.map('mapid').setView([51.505, -0.09], 13);

    L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        maxZoom: 18,
        id: 'mapbox/streets-v11',
        tileSize: 512,
        zoomOffset: -1,
        accessToken: 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw'
    }).addTo(map);


var markers = [];
$.each($('.marker'), function () {
    var marker = [];
    var lat = $(this).attr('data-lat');
    var lng = $(this).attr('data-lng');
    marker = [lat, lng];
    markers.push( marker );
});

    for (var i = 0; i < markers.length; i++) {
        marker = new L.marker([markers[i][1], markers[i][2]]).bindPopup(markers[i][0]).addTo(map);
    }
});

An Array is starting with the index 0. So lat = 0, lng = 1:

for (var i = 0; i < markers.length; i++) {
        marker = new L.marker([markers[i][0], markers[i][1]]).bindPopup(markers[i][0]).addTo(map);
}

It is also possible to use the array directly, because the array has only lat and lng:

for (var i = 0; i < markers.length; i++) {
        marker = new L.marker(markers[i]).bindPopup(markers[i][0]).addTo(map);
}

Pan to the markers

Add your markers to a L.FeatureGroup then you can move / pan the map to the markers after creation:

var fg = L.featureGroup().addTo(map);
for (var i = 0; i < markers.length; i++) {
        marker = new L.marker(markers[i]).bindPopup(markers[i][0]).addTo(fg);
}
map.fitBounds(fg.getBounds())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM