What is the best way to load KML layers on Leaflet? - leaflet

I have to load a KML layer on a Leaflet app. After some browsing I found a library called leaflet-kml that does this. There are two ways that I can load the KML layer: either by the KML layer's URI or a KML string. The KML is stored in a server and I have backend code that retrieves both the URI and string representation.
Here is the approach using the URI.
function LoadKML(containerName, name)
{
let kmlURL = GetKmlURI(containerName, name);
let kmlLayer = new L.KML(kmlURL);
map.addLayer(kmlLayer);
}
Here is the approach using the kml string.
function LoadKML(containerName, name)
{
let kmlString = GetKmlString(containerName, name);
let kmlLayer = new L.KML.parseKML(kmlString);
map.addLayer(kmlLayer);
}
I could not get a URL with the first method due to the CORS restriction. The second method returns a string, but could not be parsed correctly.
KML.js:77 Uncaught TypeError: this.parseStyles is not a function
at new parseKML (KML.js:77)
at LoadKML (Account:470)
at Account:461
How should I call the function in leaflet-kml? Are there any libraries that can easily load KML into leaflet?

You can use leaflet-omnivore. It is the best plugin for loading KML files (https://github.com/mapbox/leaflet-omnivore)
var kmlData = omnivore.kml('data/kmlData.kml', null, customLayer);

There is the plugin leaflet-kml
https://github.com/windycom/leaflet-kml
using it you can write your code like this:
<head>
<script src="L.KML.js"></script>
</head>
<script type='text/javascript'>
// Make basemap
const map = new L.Map('map', {center: new L.LatLng(58.4, 43.0), zoom: 11},)
, osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')
map.addLayer(osm)
// Load kml file
fetch('Coventry.kml')
.then( res => res.text() )
.then( kmltext => {
// Create new kml overlay
parser = new DOMParser();
kml = parser.parseFromString(kmltext,"text/xml");
console.log(kml)
const track = new L.KML(kml)
map.addLayer(track)
// Adjust map to show the kml
const bounds = track.getBounds()
map.fitBounds( bounds )
})
</script>
</body>
It should work, rgds

You were close! The parseKML requires a parsed DOM xml. The result is a list of features, which you have to wrap as a layer too.
function LoadKML(containerName, name)
{
let kmlString = GetKmlString(containerName, name);
const domParser = new new DOMParser();
const parsed = parser.parseFromString(userLayer.kml, 'text/xml');
let kmlGeoItems = new L.KML.parseKML(parsed); // this is an array of geojson
const layer = L.layerGroup(L.KML.parseKML(parsed));
map.addLayer(layer);
}

Related

How to update geojson markers periodically

What I am trying to do is to use Leaflet with OSM map,
and load data from PHP in GeoJSON format + update periodically.
I can manage to display a map, load data, but do not know how to update points instead of still adding a new ones.
function update_position() {
$.getJSON('link_to_php', function(data) {
//get data into object
var geojsonFeature = JSON.parse(data);
// how to remove here old markers???
//add new layer
var myLayer = L.geoJSON().addTo(mymap);
//add markers to layet
myLayer.addData(geojsonFeature);
setTimeout(update_position, 1000);
});
}
update_position();
have tried mymap.removeLayer("myLayer"); but this seems to now work inside of function. Please help
L.geoJSON extends from LayerGroup which provide a function named clearLayers(docs), so you call that to clear markers from the layer.
Also, it is recommended that you put the layer variable outside the function:
var geoJSONLayer = L.geoJSON().addTo(mymap);
function update_position() {
$.getJSON('link_to_php', function(data) {
//get data into object
var geojsonFeature = JSON.parse(data);
geoJSONLayer.clearLayers();
//add markers to layet
geoJSONLayer.addData(geojsonFeature);
setTimeout(update_position, 1000);
});
}
update_position();

Get Marker Feature Instance in MapBox

I'm new to mapbox GL JS and am following this example:
Add custom markers in Mapbox GL JS
https://www.mapbox.com/help/custom-markers-gl-js/
Let's say I modify the example above to include 100 different animal markers. How do I change the draggable property of a specific marker after it has been added to the map?
Example: Change the draggable property of the dog marker.
It would be nice to do something like this:
map.getMarker('dog').setDraggable(true);
I don't see a way to query any of the markers added to my map or modify a specific marker's properties like setLatLng, setDraggable after they have been added to a map. There is no method to get the collection of markers added to a map. Thanks for any help!
For change marker property like draggable check its api. IE https://www.mapbox.com/mapbox-gl-js/api/#marker#setdraggable
Mapbox custom marker is build by html element. If you want to change visual display of custom marker element, you should update Its inside html. For example, here are 2 functions I use to create a div with image background then return it as a image marker
/**
* #function CustomMarkerWithIcon(): constructor for CustomMarker with image icon specify
* #param lnglat: (LngLat) position of the marker
* map: (Map) map used on
* icon: (image) object for custom image
*/
function CustomMarkerWithIcon(lnglat, map, icon) {
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url("' + icon.url + '")';
el.style.backgroundSize = 'cover';
el.style.width = icon.size.width;
el.style.height = icon.size.height;
el.style.zIndex = icon.zIndex;
return new mapboxgl.Marker(el)
.setLngLat(lnglat)
.addTo(map);
}
/**
* #function ChangeMarkerIcon(): change marker icon
* #param marker: (marker) marker
* icon: (image) object for custom image
*/
function ChangeMarkerIcon(marker, icon) {
var el = marker.getElement();
el.style.backgroundImage = 'url("' + icon.url + '")';
}
You're right: Mapbox GL JS doesn't store references to markers. However, you can store your own references to the markers in an array at the time that you generate them.
In this example below, I am looping over a set of GeoJSON point features and creating a custom HTML marker for each:
let markersArray = [];
geojson.features.forEach(feature => {
// create a HTML element for each feature
let el = document.createElement("div");
el.className = "marker";
el.innerHTML = `
<img src="custom-marker.png" height="20px" width="20px" />
<span class="marker-label">${feature.properties.name}</span>
`;
// make a marker for each feature and add to the map
let marker = new mapboxgl.Marker({
element: el,
anchor: "top"
})
.setLngLat(feature.geometry.coordinates)
.addTo(map);
// add to my own array in an object with a custom 'id' string from my geojson
markersArray.push({
id: feature.properties.id,
marker
});
});
This id string can be whatever you want. You can even store other parameters if you want to be able to query other things, like latitude/longitude:
markersArray.push({
id: feature.properties.id,
coordinates: feature.geometry.coordinates,
marker
});
Then, if I want to access the marker's instance members (like setDraggable), I can use Array.find() to return the first instance that matches my search parameters in markersArray:
let someIdQuery = "some-id";
let queriedMarkerObj = markersArray.find(
marker => marker.id === someIdQuery
);
queriedMarkerObj.marker.setDraggable(true);
(Note that Array.find() just returns the first instance in the array that matches your condition. Use something like Array.filter() if you want to be able to query for more than one marker.)

Defining Leaflet map as dynamic map id (Cannot read property '_container' of undefined)

I have 2 different divs which using by leaflet as map object. I want to define my map objects into a function such as
html
<div id="mymap"></div>
<div id="mymap2"></div>
javascript
var map;
function define_map(map_id) {
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osm = L.tileLayer(osmUrl, {
maxZoom: 7
}),
map = new L.Map(map_id, {
center: new L.LatLng(51.505, -0.04),
zoom: 7
}),
drawnItems = L.featureGroup().addTo(map);
});
define_map("mymap");
define_map("mymap2");
$(".btnmarker").on("click", function() {
console.log(map);
L.DomUtil.addClass(map._container, 'my_crosshair-cursor-enabled'); // ON THIS LINE GETTING ERROR CODE Cannot read property '_container' of undefined
selected_tool = $(this).attr("id");
});
There is no problem, my maps seems working good until accessing features of them from button click event (this button will add a marker class to a map which i clicked on it)
But i'm getting map is not defined error. map is a variable and defined on top line of page.
Thanks inadvance

Mapbox Filter Markers loaded via json

I am looking for solution to add filter (not checkbox) to my site. I have this code loading blank map from Mapbox and added Markers from JSON file. I was trying to add setFilter function, but probably I am using it wrong. I would like to filter items by category property from my JSON file.
<script>
L.mapbox.accessToken = '*************';
var baseLayer = L.mapbox.tileLayer('test****');
var markers = L.markerClusterGroup();
// CALL THE GEOJSON HERE
jQuery.getJSON("locations.geojson", function(data) {
var geojson = L.geoJson(data, {
onEachFeature: function (feature, layer) {
// USE A CUSTOM MARKER
layer.setIcon(L.mapbox.marker.icon({'marker-symbol': 'circle-stroked', 'marker-color': '004E90'}));
// ADD A POPUP
layer.bindPopup("<h1>" + feature.properties.title + "</h1><p>" + feature.properties.description + "</p><p><a href=' + feature.properties.website + '>" + feature.properties.website + "</a></p>");
layer.on('mouseover', function (e) {
this.openPopup();
});
layer.on('mouseout', function (e) {
this.closePopup();
});
}
});
markers.addLayer(geojson);
// CONSTRUCT THE MAP
var map = L.map('map', {
searchControl: {layer: markers},
zoom: 6,
center: [51.505, -0.09],
maxZoom: 13
})
.setView([62.965, 19.929], 5)
.fitBounds(markers.getBounds());
baseLayer.addTo(map);
markers.addTo(map);
L.control.fullscreen().addTo(map);
});
</script>
Could you please help me add filter buttons (something like here: https://www.mapbox.com/mapbox.js/example/v1.0.0/filtering-markers)
PS: I think I tried all examples from Mapbox website, yet seems my skills are very limited here.
Thank you
I was trying to add setFilter function, but probably I am using it wrong. I would like to filter items by category property from my JSON file.
This code example is using L.geoJson to load the markers into your map. Like the Mapbox example, you'll need to use L.mapbox.featureLayer instead, since it includes the setFilter function and L.geoJson does not.
tmcw's answer is correct, L.mapbox.featureLayer is confusing
this tutorial helped me!
https://www.mapbox.com/mapbox.js/example/v1.0.0/custom-marker-tooltip/

Working with openlayers and typescript classes

/// <reference path="openlayers.d.ts" />
class MapComponent {
element: HTMLElement;
map: OpenLayers.Map;
constructor(element: HTMLElement) {
// Setup our map object
this.element = element;
this.map = new OpenLayers.Map(this.element);
}
init() {
// Setup our two layer objects
var osm_layer_map = new OpenLayers.Layer.OSM("OSM");
// Add layers to the map
this.map.addLayers([osm_layer_map]);
// Add a layer switcher control
this.map.addControl(new OpenLayers.Control.LayerSwitcher({}));
// Zoom the map to the max extent
if (!this.map.getCenter()) {
this.map.zoomToMaxExtent();
}
}
}
window.onload = () => {
var el = document.getElementById('map');
var mc = new MapComponent(el);
mc.init();
}
I have the above piece of code to work with a simple HTML file with only 1 of ID, 'map' with style: height and width # 500px.
I have tried several other ways to get the map to display but so far all i got was a white page (blank).
Can anybody point me in the right direction?
Solutions tried so far:
using jquery with ready function
replace window.onload with a call direct from the html, <script><script/>
place document.getElementById() in the new OpenLayers.Map(here); when first creating this.map
placing the window.onload call above and below (currently)
using export class or public init() or both
As of now, I just want it to work.
Seems that creating the map with the element provided and later defining the options doesn't work.
Instead either initialize the map with options
var options = {
projection: "EPSG:3857",
maxExtent: new OpenLayers.Bounds(-200000, -200000, 200000, 200000),
center: new OpenLayers.LonLat(-12356463.476333, 5621521.4854095)
};
this.map = new OpenLayers.Map(this.element, options);
Or call this.map.render(this.element) at the end of your init method.
Also make sure your div is actually visible and has some size specified, otherwise it might be not visible...