Last active
March 28, 2024 13:48
-
-
Save fburatti/54338e6e9106a402847c499263e55e99 to your computer and use it in GitHub Desktop.
Open street map with Leaflet.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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:'© <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