Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Open street map with Leaflet.js
// leaflet.js required
// the properties array can contain multiple pointers (markers) and is included with wordpress wp_localize_script
//var properties = [{"title":"Some title","lat":"42.75410269263614","lng":"12.758049219846725","thumb":"http:\/\/www.mysite.ext\/wp-content\/uploads\/2016\/05\/image.jpg","url":"http:\/\/www.www.mysite.ext\/"}];
var map;
function render_map( $el ) {
var $markers = properties;
map = L.map($el[0], {
minZoom : 0,
maxZoom : 18,
zoomSnap : 0.1,
zoomDelta: 0.5,
scrollWheelZoom : false,
touchZoom:true,
dragging:!L.Browser.mobile
});
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution:'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'}).addTo(map);
/*var baseLayers = {
"Mapbox": mapbox,
"OpenStreetMap": osm
};
L.control.layers(baseLayers).addTo(map);
*/
map.markers= [];
$.each($markers, function (index, value) {
add_marker( jQuery(this), map);
});
map.setView([0, 0], 4);
center_map( map );
map.on('resize', function () {
center_map( map );
});
}
function add_marker( $marker, map) {
var marker_content = '<div class="map-property clearfix">'+
'<p>'+$marker[0].title+'</p>'+
'<a class="map-image" href="'+$marker[0].url+'"><img class="property-thumb" src="'+$marker[0].thumb+'" alt="'+$marker[0].title+'"/></a>' +
'<a class="btn btn-standard" href="'+$marker[0].url+'">Dettagli</a>' +
'</div>'
var marker = L.marker([$marker[0].lat, $marker[0].lng]).addTo(map).bindPopup(marker_content);
/*var marker = L.circleMarker([$marker[0].lat, $marker[0].lng], {
radius:10,
fillColor: $marker[0].color,
color: "#000",
weight: 2,
opacity: 1,
fillOpacity: 1,
}).addTo(map).bindPopup(marker_content);*/
//.bindTooltip("1", {permanent: true, className: "my-label", offset: [0, 0], direction: 'center' })
map.markers.push( marker );
}
function center_map( map ) {
console.log(map.markers);
if ( map.markers.length == 1 ) {
map.setView(map.markers[0].getLatLng(),15);
// map.setZoom( 16 );
}
else {
var group = new L.featureGroup(map.markers);
map.fitBounds(group.getBounds().pad(0.2));
}
}
jQuery(function($) {
if ($("#acf-map").length) {
render_map( $("#acf-map") );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.