I have leaflet map that draws markers from geojson and binds popups to them. GeoJSON feature collection is stored in geojsonFeature variable. The code looks like this:
<script>
var map = L.map('map').setView([42.652, 18.102], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var sidebar = L.control.sidebar('sidebar').addTo(map);
function onEachFeature(feature, layer) {
var popupContent = '<h3>'+feature.properties.Naziv+'</h>';
if (feature.properties.Slika) {
popupContent += '<br /><img src="slike/'+feature.properties.Slika+'.jpg" alt="Slika" style="width:300px;">';
}
layer.bindPopup(popupContent);
}
L.geoJSON(geojsonFeature, {
onEachFeature: onEachFeature
}).addTo(map);
</script>
This works fine, but I want to add a list with features outside the map. The list would be clickable and an onClick event would pass feature id to the function that zooms the map on selected feature and opens the popup.
The only problem is that I don't know how to zoom map to the feature and open the popup programmatically using the point's ID from source GeoJSON.
Found a way to work around this. I added a clickable list of features outside of map with ID-s and "ref" class. Then I made the following jQuery listener:
$(".ref").click(function () {
//extract ID from list HTML element
var id=eval(this.id);
//find object with extracted ID in original GeoJSON
//use object's coordinates and features to pan the map and display popup
map.setView([geojsonFeature.features[id].geometry.coordinates[1], geojsonFeature.features[id].geometry.coordinates[0]], 16);
var popupData = '<h3>'+geojsonFeature.features[id].properties.Naziv+'</h>';;
if(geojsonFeature.features[id].properties.Slika) {
popupData += '<br /><img src="slike/'+geojsonFeature.features[id].properties.Slika+'.jpg" alt="Slika" style="width:300px;">';
}
var popup = L.popup()
.setLatLng([geojsonFeature.features[id].geometry.coordinates[1], geojsonFeature.features[id].geometry.coordinates[0]])
.setContent(popupData)
.openOn(map);
});
Related
I have map , where I have Markers.When I click on Marker, it shows name of marker on popup using openPopup().
getBindPopup: function (e) {
var element = e;
var latlng = [element.lat, element.lng];
return L.popup()
.setLatLng(latlng)
.setContent('' + element.name + '')
.openPopup();
}
This is the function , I am using to show Popup on marker.
I am calling this function in another function and then Markers getting update :
var popup = App.elementData.getBindPopup(element);
//below line :calling getBindPopup function
App.map.Markers[element.id] = L.marker(latlng, element).bindPopup(popup);
// This line will update all Markers on Map
App.map.Count._update(App.map.Markers);
But after App.map.Count._update(App.map.Markers); popup get disappear.
I need popup even after markers updates on the map.
Please suggest.
Thank you.
so I'm making a website using leaflet with dozens of base maps. I want to incorporate information about each map that is only visible if the user wants it. To do this, I would like to make an overlay map with popups, but I want the popups to change depending on the base map selected by the user.
How would I go about doing this?
Thank You So Much
You need to either use a plugin that keeps track of the base maps for you (like active layers) or you need to do it yourself.
If you are using the Leaflet layers control, you can subscribe to the basemapchange event to do this easily.
You need two things: active base layer management (easy) and dynamic popups (not too hard)
To wit:
First, here is the event handler to track active base layer when it changes.
map.on("baselayerchange",
function(e) {
// e.name has the layer name
// e.layer has the layer reference
map.activeBaseLayer = e.layer;
console.log("base map changed to " + e.name);
});
Because using L.marker().bindPopup() creates the popup content right there and does not support callbacks, you must manually create the popups in response to click event by calling map.openPopup() with your dynamic html (dynamic because it uses a variable: the active basemap name)
marker.on("click", function(e) {
var html = "Current base layer: <br/><b>" + map.activeBaseLayer.options.name + "<b>";
map.openPopup(html,
e.latlng, {
offset: L.point(1, -24)
});
});
Here is a working example on JS fiddle: http://jsfiddle.net/4caaznsc/
Working code snippet also below (relies on Leaflet CDN):
// Create the map
var map = L.map('map').setView([39.5, -0.5], 5);
// Set up the OSM layer
var baseLayer1 = L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
name: "Base layer 1"
});
var baseLayer2 = L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
name: "Base layer 2"
});
// add some markers
function createMarker(lat, lng) {
var marker = L.marker([lat, lng]);
marker.on("click", function(e) {
var html = "Current base layer: <br/><b>" + map.activeBaseLayer.options.name + "<b>";
map.openPopup(html,
e.latlng, {
offset: L.point(1, -24)
});
});
return marker;
}
var markers = [createMarker(36.9, -2.45), createMarker(36.9, -2.659), createMarker(36.83711, -2.464459)];
// create group to hold markers, it will be added as an overlay
var overlay = L.featureGroup(markers);
// show overlay by default
overlay.addTo(map);
// show features
map.fitBounds(overlay.getBounds(), {
maxZoom: 11
});
// make up our own property for activeBaseLayer, we will keep track of this when it changes
map.activeBaseLayer = baseLayer1;
baseLayer1.addTo(map);
// create basemaps and overlays collections for the layers control
var baseMaps = {};
baseMaps[baseLayer1.options.name] = baseLayer1;
baseMaps[baseLayer2.options.name] = baseLayer2;
var overlays = {
"Overlay": overlay
};
// create layers control
var layersControl = L.control.layers(baseMaps, overlays).addTo(map);
// update active base layer when changed
map.on("baselayerchange",
function(e) {
// e.name has the name, but it may be handy to have layer reference
map.activeBaseLayer = e.layer;
map.closePopup(); // any open popups will no longer be correct; take easy way out and hide 'em
});
#map {
height: 400px;
}
<script src="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.js"></script>
<link href="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.css" rel="stylesheet"/>
<div id="map"></div>
I want to create a panTo -function. When I click a link the map pans to the coordinates. But im not sure how to pass the value to the function. I'm starting with giving the link the Pointfield (pt) value like this:
Link
Then I've been trying this:
$("#dialog").on("click", ".marker", function(e) {
e.preventDefault();
map.panTo($(this).attr("value"));
});
That didn't work. I think it's a scope-issue where the function cant read the 'map' variable because it's not under the initial map script.
So my next idea is to create a "panTo"- function and place it under the inital map script (which would be the right scope) and call that function from the click event instead. Not sure it would work but Im wondering how to pass it the "value" from the link?
Thanks for your answers!
You can add navigation to your map by utilizing data attributes in your HTML. Save the latitude,longitude and zoom to something like data-position and then call those values with some JavaScript when the user clicks on the anchor tag. Here's some code to illustrate.
<div id="map">
<div id="map-navigation" class="map-navigation">
<a href="#" data-zoom="12" data-position="37.7733,-122.4367">
San Francisco
</a>
</div>
</div>
<script>
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade'
}).addTo(map);
document.getElementById('map-navigation').onclick = function(e) {
var pos = e.target.getAttribute('data-position');
var zoom = e.target.getAttribute('data-zoom');
if (pos && zoom) {
var loc = pos.split(',');
var z = parseInt(zoom);
map.setView(loc, z, {animation: true});
return false;
}
}
</script>
I'm working on functionality to take snapshot of google map with polylines and open popup window on polyline click on google map.
The snapshot of google map with polylines is working
but it will not able to take snapshot open popup window on polyline.
polyline are showing on sanpshot picture but info window are not showing .
Here is code to take snapshot.
This code is to initialize the code control on javascript onload :
var snapShotControlOptions = { hidden: true };
snapShotControlOptions.buttonLabelHtml="<snap id='snap' style='display:none' >snap</span>"
snapShotControl = new SnapShotControl(snapShotControlOptions);
map.addControl(snapShotControl);
here is the method take snap to take the sanp shot of google map .
function takeSnap() {
//static map size
var sizeStr = "640x640";
var imgSize = "";
if (sizeStr != "") {
var sizeArray = sizeStr.split("x");
imgSize = new GSize(sizeArray[0], sizeArray[1]);
}
snapShotControl.setMapSize(imgSize);
var format = "jpg";
snapShotControl.setFormat(format);
var url = snapShotControl.getImage();
// document.getElementById("snapshot_canvas").src = url;
SaveImage(url);
//
}
//this will add polyline overlay to draw line on google map with different color of polyline on google map .
var polyline = directionsArray[num].getPolyline();
polyline.setStrokeStyle({ color: streetColor, weight: 3, opacity: 0.7 });
polyline.ssColor=streetColor;
map.addOverlay(polyline);
///this code will open the pop info window on polyline those polyline created on google map
and problem is their these pop window not included on sanpshot when i take sanpshot of google map.
var MousePoint = "";
var marker;
GEvent.addListener(map, "mousemove", function (point) {
MousePoint = new GLatLng(point.lat(), point.lng());
});
GEvent.addListener(polyline, "click", function () {
map.openInfoWindowHtml(MousePoint, headMarkerHtml);
});
GEvent.addListener(polyline, "mouseout", function () {
// map.closeInfoWindow();
});
can you please tell who i pass popup window in polyline overlay .
i have use javascript file snapshotcontrol.js to take the snapshot.
from the snapshotcontrol source
This library makes it easy to generate an image "snapshot" of your
interactive map, using the Google Static Maps API.
Static maps doesn't support info windows or anything like adding custom text to the map
https://developers.google.com/maps/documentation/staticmaps/index
You could draw the map on a canvas within the browser then
draw the info window on top of that using this http://html2canvas.hertzen.com/
and then download the canvas content
I've got the following Google map on my website..
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(53.347247,-6.259031), 13);
map.setUIToDefault();
GEvent.addListener(map, "click", function(overlay, latLng)
{
// display the lat/lng in your form's lat/lng fields
document.getElementById("lat").value = latLng.lat();
document.getElementById("lng").value = latLng.lng();
});
}
}
What would I need to add / edit so that whenever a user clicked a location on the map a pin / balloon / any kind of indicator would be dropped at the location they clicked?
Thanks.
All you have to do is add this to your existing addListener call:
if (latLng) {
marker = new GMarker(latLng, {draggable:true});
map.addOverlay(marker);
}
See this article linked by Google in their API information for an even more advanced example that lets your users edit the map data.
Update: Changed case of 'l' to 'L' in latLng.