We developed a web page where we are showing health facility locations of a country on a map. We used Leaflet for the map display. We actually do not need to display the online map tiles in the background. If we can only show a vector country map that would also be OK. I came to know that tiles can be downloaded and saved offline in Leaflet etc, but not interested in that direction.
What I want is available in this page
Where Leaflet is used but the world map online tiles are not displayed. But the code is quite complex to understand. Is there any easy example or guidance to do what I need?
This is actually quite easy when using a L.GeoJSON layer. First off you would need to find the correct GeoJSON for the region you want to display. For instance, here are some for the US: http://eric.clst.org/Stuff/USGeoJSON. Next create a map like you would normally do:
var map = new L.Map('map', {
'center': [0, 0],
'zoom': 0
});
Then you would need to fetch/load your GeoJSON data into your script using ajax via jQuery or something else and use that to initialize a GeoJSON layer and add that to your map:
// jQuery ajax request
$.ajax({
// url with your geojson data file
'url': 'my.geo.json',
// return json object, not as string
'dataType': 'json',
// on success handle result
'success': function (result) {
// Initialize GeoJSON layer and add to map
var layer = new L.GeoJSON(result).addTo(map);
// Fit map to bounds of your GeoJSON
map.fitBounds(layer.getBounds());
}
});
That's it. You can find lots of GeoJSON datasets online and if you want to know more about the L.GeoJSON i would recommend reading the reference i linked earlier and this tutorial: http://leafletjs.com/examples/geojson.html
Related
I am modifying features from layer and would like to use similar to "setData()" to a vector layer? From googling some places i read that its not possible to use that setData function to vectors and only to geojsons.
What i am doing is first i get the feature properties from layer
let features = this.map.queryRenderedFeatures({layers:["maakunta-fills"]}).map(item=>{
const copied = {...item}
copied.properties.modified = "some_modified_value"
return copied;
});
and then my wish is i can do something like : this.map.getSource("sourcename").setData(features)
But mapbox will throw error by saying setData is not function (i assume because this "sourcename" is a vector tile. Which looks like this:
this.map.addSource("maakunta", {
type: "vector",
tiles: [tileServiceURL + "base.maakunta/{z}/{x}/{y}.pbf"],
promoteId: "id"
});
The best way to do this is by using setFeatureState. It will not change the vector data but you can change the style and intercept any click events and push the updated data. This of course is limited to the current client session. Ideally you would be updating the source data in a database for example so that when a new user views a new db tile request they will have access to the new data.
I'm working on a map on whitch I want to draw the path I drove with my motorcycle. For this I want to use mapbox opengl because of the wonderful graphical features. I have dificulties to understand the different kind of sources that Mapbox offers (https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/). I collect the data with my self developed logger (lat, lng, speed, acc, gyro, leaning angle, alt) and can export them in any kind of file or format. But as far as I understood, geo.json files are not able to support metadata. So I looked up the "Tiled Sources" but here I getting into trouble. Do I need a mapper from Mapbox from my file and then consume the data to mapbox or do i have a direct options to import my CSV and define the data columns.
But as far as I understood, geo.json files are not able to support metadata.
Incorrect. You can store any metadata you like either on the properties attribute of a Feature, or at the top level of a FeatureCollection.
So I looked up the "Tiled Sources" but here I getting into trouble.
You don't want a tiled source.
Do I need a mapper from Mapbox from my file and then consume the data to mapbox or do i have a direct options to import my CSV and define the data columns.
Probably what you want is to convert the CSV to GeoJSON. You can even do it dynamically in your code front end.
After loading the CSV (using something like D3's csv method), you can do something like this:
const geojson = {
type: 'FeatureCollection',
features: rows.map((row, id) => ({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [+row.longitude], +row.latitude],
},
properties: {
id,
...row
}
}))
}
map.addSource('mysource', { type: 'geojson', data: geojson });
I have created a Mapbox style using Mapbox Studio and set it to be used over WMTS. The URL of the style is:
https://api.mapbox.com/styles/v1/username/styleId/wmts?access_token=token
where styleId, username and token are variable fields.
When I try to create a WMTS layer in OpenLayers using the url above, the tileGrid is created successfully using createFromCapabilitiesMatrixSet but I get a response error Invalid query param layer from Mapbox.
After some investigation, I noticed that:
The response error persists for all query parameters that are appended from OpenLayers when creating the tile load function. It looks like that Mapbox does not recognise them properly.
OpenLayers website and Mapbox also give examples on using XYZ layers for integration between them.
So, is this some kind of unsupported feature of OpenLayers or do I need to configure anything additional when creating the WMTS OpenLayers?
It's much simpler to set up as a standard OpenLayers XYZ layer using
url: 'https://api.mapbox.com/styles/v1/username/styleId/tiles/{z}/{x}/{y}?access_token=token'
as in the examples.
Mapbox provides WMTS support for compatibility with some other systems. It can also be used in OpenLayers, the setup would be
var parser = new ol.format.WMTSCapabilities();
fetch('https://api.mapbox.com/styles/v1/username/styleId/wmts?access_token=token').then(function(response) {
return response.text();
}).then(function(text) {
var layer = new ol.layer.Tile({
source: new ol.source.WMTS(
ol.source.WMTS.optionsFromCapabilities(parser.read(text), {
layer: 'styleId',
matrixSet: 'EPSG:3857'
})
)
});
....
....
....
....
});
Both methods will ultimately load the same tile urls, so there's no advantage in using WMTS where XYZ is supported.
I have a Mapbox GL JS implementation that gets its data from a vector mbtiles file that I downloaded from www.openmaptiles.com. I use tileserver.php with the mbtiles file to serve the PBF data, which Mapbox GL can use to display the map.
Is there any way to extract data from this in a specific area or lng/lat-pair using Javascript ?
Once you have added your sources to a Mapbox-GL-JS map and created a layer ("roads", say) that references it, you can use map.querySourceFeatures() to get features at a given screen location. To turn a lat/long into a screen location, you need to use map.project().
So all up:
var features = map.queryRenderedFeatures(map.project([mylng, mylat]), { layers: ['roads'] });
var p = features && features[0] && features[0].properties;
p now contains the properties of the object at that location.
I'm learning how to use Leaflet to make online interactive maps for public health purposes (experienced ArcGIS user, Mapbox TileMill). I'm taking it slow so I understand each piece of code, and I'm working from the Leaflet choropleth example as I want to make choropleth maps. The current task I'm stuck on is how to correctly add topoJSON data to a Leaflet map. I've tried the following code to convert the us states geoJSON to topoJSON, but it hasn't worked. Any suggestions?
var geojson;
var test = topojson.feature(us-states-topo, us-states-topo.objects.layer1 );
geojson = L.geoJson(test, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
I've reviewed the topoJSON API reference, but I'm sure I must be making a simple error as I am a beginner to JavaScript in general. Thank you all for your help!
Best
Eli
I'd recommend using your browser debug tools to start through debugging this.
var test = topojson.feature(us-states-topo, us-states-topo.objects.layer1 );
This is not valid JavaScript: us-states-topo is not a valid variable name, since -s are not permitted.