I managed to create map with leaflet.js & jQuery mobile.
Now I need to get rid of jQuery mobile and just use jQuery instead.
Everything works just fine, but I can't click the polygons which I draw on the map anymore. It worked with jQuery mobile before.
Any hints?
here is my simplified code:
var map = L.map('map', {
zoomControl: false
});
L.tileLayer('http://{s}.tile.cloudmade.com/**apikey***/997/256/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade',
maxZoom: 18
}).addTo(map);
For the polygons:
var geojsonFeature = { "type": "Polygon","coordinates": value.polygon};
var polycolor = getGebColor(value.geb_nr);
var geojsonStyle = {"color": polycolor};
polygons[i] = L.geoJson(geojsonFeature, {style: geojsonStyle}).addTo(map);
// make clickable
polygons[i].on('click', function(e) {
if (lastMarker) {
map.removeLayer(lastMarker);
}
var url = "http://*****/tugetherMap.php?callback=&id="+value.id+"&type=B";
markers[i] = L.marker([value.point[1], value.point[0]]).addTo(map);
gebName = value.nameLang;
markers[i].bindPopup("<a class='gebOnMap' href='gebaeude.html' >"+gebName+"</a>").openPopup();
lastMarker = markers[i];
});
the polygons[i].on('click',...) is the part which does not work anymore. It works for map.on('click',...)
You need to bind each of your polygons to a click event handler, like so.
L.geoJson(geojsonFeature, {
onEachFeature: function(feature, layer) {
layer.on('click', function(e) {
// Do whatever you want here, when the polygon is clicked.
});
}
}).addTo(map);
Had a issue with this and solved it with the following
function onEachFeature(feature, layer) {
// Do all your popups and other binding in here
// does this feature have a property named popupContent?
if (feature.properties && feature.properties.popupContent) {
layer.bindPopup(feature.properties.popupContent);
}
}
var geojsonFeature = {
"type": "Feature",
"properties": {
"name": "Coors Field",
"amenity": "Baseball Stadium",
"popupContent": "This is where the Rockies play!"
},
"geometry": {
"type": "Point",
"coordinates": [-104.99404, 39.75621]
}
};
L.geoJson(geojsonFeature, {
onEachFeature: onEachFeature
}).addTo(map);
In your code I guess it would be
polygons[i] = L.geoJson(geojsonFeature, {onEachFeature: onEachFeature,
style: geojsonStyle}).addTo(map);
function onEachFeature(feature, layer) {
// Some jazz and magic you need to do with your layer and feature objects
}
The solution for me was to downgrade Leaflet to 0.7.3 or upgrade to 1.0-beta2 (latest version at the time of writing).
Related
I have a geoJSON object that is added to the map like this:
L.geoJSON(seine_mar).addTo(map)
Which creates the following:
I would like to add a text on hover of this zone. It is possible with markers, like this for example:
L.marker([value.lat, value.lon], { title: "Hi there"}).addTo(map);
How could I achieve the same with the geoJSON, resulting in displaying a text on hover ? According to the docs, there is no such property as title or label.
Example of desired result (fear my paint skills):
Try using bindTooltip() with permanent option
https://leafletjs.com/reference-1.7.1.html#tooltip
var map = L.map('map').setView([39.74739, -105], 13);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'Imagery © Mapbox',
id: 'mapbox/light-v9',
tileSize: 512,
zoomOffset: -1
}).addTo(map);
var campus = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-105.00432014465332, 39.74732195489861],
[-105.00715255737305, 39.74620006835170],
[-105.00921249389647, 39.74468219277038],
[-105.01067161560059, 39.74362625960105],
[-105.01195907592773, 39.74290029616054],
[-105.00989913940431, 39.74078835902781],
[-105.00758171081543, 39.74059036160317],
[-105.00346183776855, 39.74059036160317],
[-105.00097274780272, 39.74059036160317],
[-105.00062942504881, 39.74072235994946],
[-105.00020027160645, 39.74191033368865],
[-105.00071525573731, 39.74276830198601],
[-105.00097274780272, 39.74369225589818],
[-105.00097274780272, 39.74461619742136],
[-105.00123023986816, 39.74534214278395],
[-105.00183105468751, 39.74613407445653],
[-105.00432014465332, 39.74732195489861]
]
]
}
};
L.geoJSON(campus)
.bindTooltip('Hi there', {
permanent: true,
direction: 'center'
})
.addTo(map);
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<div id='map'></div>
You can use the onEachFeature function of L.geoJSON() to loop through all layers and then add a Tooltip with layer.bindTooltip("HI") to it.
L.geoJSON(seine_mar,{
onEachFeature: function(feature, layer){
layer.bindTooltip('Hi there', {permanent: true}).openTooltip();
// or over a feature property layer.bindTooltip(feature.properties.customTitle)
}
}).addTo(map)
As you see in this fiddle , I have a polygon like this:
var data = [{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[2.504410743713379,44.28253972334941],
[2.504410743713379,44.28929846767132],
[2.5168561935424805,44.28929846767132],
[2.5168561935424805,44.28253972334941],
[2.504410743713379,44.28253972334941]
]
]
}}]
When I want to add it to my featureGroup drawnItems I use:
var geojsonLayer = L.geoJson(data);
geojsonLayer.getLayers()[0].addTo(drawnItems);
Then I decide to edit polygon I can't move it because the central move handler does not appear, But when I draw new polygon using the toolbar I have move handler.
Could you please help me?
how can I add my polygon to have move handler?
Do something like this to add every Geojson layer to drawnItems:
var geeoojson = L.geoJSON(JSON.parse(data), {
onEachFeature: function (feature, layer) {
layer.addTo(drawnItems);
}
}).addTo(map)
I am trying new to localStorage, and I am trying to save the markers that the user can create on the map.
I created this function to place markers and delete them:
var redmarker = L.icon({
iconUrl: 'http://icons.iconarchive.com/icons/paomedia/small-n-flat/48/map-marker-icon.png',
iconSize: [48, 48], // size of the icon
iconAnchor: [24, 48], // point of the icon which will correspond to marker's location
popupAnchor: [-2, -48] // point from which the popup should open relative to the iconAnchor
});
var popup = L.popup();
// On map click shows coordinates X, Y
function onMapClick(e) {
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [e.latlng.lat, e.latlng.lng]
}
}
var marker;
L.geoJson(geojsonFeature, {
pointToLayer: function(feature, latlng){
marker = L.marker(e.latlng, {
title: "Resource Location",
alt: "Resource Location",
riseOnHover: true,
draggable: true,
icon: redmarker
}).bindPopup("<<span>X: " + e.latlng.lng + ", Y: " + e.latlng.lat + "</span><br><a href='#' id='marker-delete-button'>Delete marker</a>");
marker.on("popupopen", onPopupOpen);
return marker;
}
}).addTo(map);
}
function onPopupOpen() {
var tempMarker = this;
$("#marker-delete-button:visible").click(function () {
map.removeLayer(tempMarker);
});
}
map.on('click', onMapClick);
I am not familiar with localStorage, this is new to me. Also I am trying to make the popup editable, an user input there for the user name the marker.
I saw this example of input:
http://tahvel.info/simpleStorage/example/
Something like that.
A working example of my function: http://fiddle.jshell.net/2g4h5eu5/1/
Can someone help me save the markers in localStorage?
Also my problem is that I don't know what render's the markers on leaflet after I click, so I don't know exactly what I need to save in local storage to retrieve those markers.
you can use the following functions to manage your localStorage
localStorage.setItem('favoriteflavor','vanilla');
var taste = localStorage.getItem('favoriteflavor');
// -> "vanilla"
localStorage.removeItem('favoriteflavor');
var taste = localStorage.getItem('favoriteflavor');
// -> null
check this link
also you can use jQuery Storage API plugin to make things more cross-browser
http://fiddle.jshell.net/thesane/2g4h5eu5/29/
/// Load markers
function loadMarkers()
{
var markers = localStorage.getItem("markers");
if(!markers) return;
markers = JSON.parse(markers);
markers.forEach(function(entry) {
latlng = JSON.parse(entry);
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [latlng.lat, latlng.lng]
}
}
var marker;
L.geoJson(geojsonFeature, {
pointToLayer: function(feature){
marker = L.marker(latlng, {
title: "Resource Location",
alt: "Resource Location",
riseOnHover: true,
draggable: true,
icon: redmarker
}).bindPopup("<<span>X: " + latlng.lng + ", Y: " + latlng.lat + "</span><br><a href='#' id='marker-delete-button'>Delete marker</a>");
marker.on("popupopen", onPopupOpen);
return marker;
}
}).addTo(map);
});
}
/// Store markers
function storeMarker(marker)
{
var markers = localStorage.getItem("markers");
if(!markers) {
markers = new Array();
console.log(marker);
markers.push(JSON.stringify(marker));
}
else
{
markers = JSON.parse(markers);
markers.push(JSON.stringify(marker));
}
console.log(JSON.stringify(markers));
localStorage.setItem('markers', JSON.stringify(markers));
}
// Delete Marker
function deleteMarker(lng, lat) {
var markers = localStorage.getItem("markers");
markers = JSON.parse(markers);
for(var i=0;i<markers.length;i++){
latlng = JSON.parse(markers[i]);
if(latlng.lat == lat && latlng.lng == lng)
{
markers.splice(i,1);
}
}
localStorage.setItem('markers', JSON.stringify(markers));
}
My code is this
heat = L.heatLayer([], { maxZoom: 12 }).addTo(map);
$.getJSON("js/example-single.geojson", function(data) {
var geojsosn = L.geoJson(data, {
onEachFeature: function (feature, layer) {
console.log(feature.geometry.coordinates[0] ,feature.geometry.coordinates[1]);
heat.addLatLng(feature.geometry.coordinates[0], feature.geometry.coordinates[1]);
}
});
but am getting an error "Uncaught TypeError: Cannot read property 'lat' of undefined"
please tell how to fix this, if my code is wrong somebody show me how to parse json data for heat map in mapbox
my json data is
{ "type": "FeatureCollection",
"features": [
{ "type": "Feature",
"geometry": {"type": "Point", "coordinates": [13.353323936462402, 38.11200434622822]},
"properties": {"marker-color": "#000"}
}
]
}
addLatLng probably expects L.latLng objects or something that has lat & lng properties.
var heat = L.heatLayer([], { maxZoom: 12 }).addTo(map);
$.getJSON('js/example-single.geojson', function(data) {
var geojson = L.geoJson(data, {
onEachFeature: function(feature, layer) {
feature.geometry.coordinates.forEach(function(p) {
heat.addLatLng(L.latLng(p[0], p[1]));
});
}
});
});
I am starting to use the Google Map Javascript API V3 and wish to display markers on a map, using GeoJSON. My GeoJSON is as follows:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.236112, -27.779627]
},
"properties": {
"name": "[153.236112, -27.779627]",
"description": "Timestamp: 16:37:16.293"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.230447, -27.777501]
},
"properties": {
"name": "[153.230447, -27.777501]",
"description": "Timestamp: 16:37:26.298"
}
}
]
}
And my JavaScript code to load the GeoJSON:
var map;
var marker;
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 14,
center: ${lastPosition}
});
// Load the associated GeoJSON
var url = 'fieldDataGeoJSON';
url += '?deviceId=' + deviceId + '&fieldId=' + fieldId;
map.data.loadGeoJson(url);
}
google.maps.event.addDomListener(window, 'load', initialize);
Note: the URL "fieldDataGeoJSON.." returns the GeoJSON, as you might have already figured out.
This works well: the markers are shown on the map, at the good location. But the fields "name" and "description" present in the GeoJSON are not linked to the markers, meaning that they are not displayed when I click on the marker.
I guess that the first question would be: "Is it supposed to be supported?". If not, does it mean that I have to parse the GeoJSON to add the names and descriptions? Do you have any hints on how to achieve this?
Thank you in advance for your help!
Normal Google Maps Javascript API v3 event listeners work, as do normal infowindows.
var map;
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 14,
center: new google.maps.LatLng(-27.779627,153.236112)
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Load the associated GeoJSON
var url = 'http://www.geocodezip.com/fieldDataGeoJSON.txt';
map.data.loadGeoJson(url);
// Set event listener for each feature.
map.data.addListener('click', function(event) {
infowindow.setContent(event.feature.getProperty('name')+"<br>"+event.feature.getProperty('description'));
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-34)});
infowindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
working example