Looping over data in leaflet - javascript

I have 1000 geographic data points and I have a US map. I want to create tiny circles at each of these 1000 geo data points. My data is in geojson format.
I am able create a circle at one point at a time. But how do I loop over the dataset to create circles at each point?
This is my circle code:
var circle = L.circle([64.837778, -147.716389], 500, {
color: 'black',
fillColor: '#000',
fillOpacity: 0.8
}).addTo(map);

You should use L.GeoJSON to render your data. It was made for rendering GeoJSON data. It has a pointToLayer function which you can use to render your point to circles, circlemarkers or whatever you desire. As a matter of fact the examples section on the Leaflet website has an exact example of what you are trying to accomplish:
L.geoJson(someGeojsonFeature, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, geojsonMarkerOptions);
}
}).addTo(map);
You can render single features or entire featureCollections with the GeoJSON layer, check out the examples on the site: http://leafletjs.com/examples/geojson.html
EDIT: as per request, an entire example:
First you start of with a GeoJSON featureCollection:
var featureCollection = [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-104.99, 39.73]
}
},{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [-104.96, 39.73]
}
}];
Instanciate GeoJSON layer with the featureCollection:
var geoJsonLayer = L.geoJson(featureCollection, {
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
});
}
});
Add the layer to your map instance:
geoJsonLayer.addTo(map);
Working example on plunker: http://plnkr.co/edit/RzYMrkkly3DdHMnkjvVN?p=preview

Related

mapbox: avoiding of a duplication layers at low zoom scale

I faced with problem that my layers are duplicating at low zoom scale.
Using mapbox-gl-leaflet, it's combining mapbox map with leaflet. But first of all I'm using mapbox layers so seems the problem is in mapbox.
Here is code example:
var map = L.map('map', {minZoom: 1 }).setView([38.912753, -77.032194], 1);
var gl = L.mapboxGL({
accessToken: "access_token",
style: 'mapbox://styles/mapbox/bright-v8'
}).addTo(map);
gl._glMap.on('load', () => {
gl._glMap.addLayer({
"id": "line-example",
"type": "line",
"source": {
"type": "geojson",
"data": {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [[28.2, 60.0], [-10, -13]]
}
}
},
"layout": {
"line-join": "round",
"line-cap": "round"
},
"paint": {
"line-color": "rgba(13, 12, 39, .7)",
"line-width": 6
}
});
});
And here is the result:
How can I fix this problem with duplicating? I need that my layer appear only in one 'world'.
You can prevent the map from rendering multiple copies of the world (and the layer) by setting renderWorldCopies to false.
Something like this would work:
var gl = L.mapboxGL({
accessToken: "access_token",
style: 'mapbox://styles/mapbox/bright-v8',
renderWorldCopies: false,
}).addTo(map);
For more options, check API spec here: https://docs.mapbox.com/mapbox-gl-js/api/
Try to add in maxBounds [ [-180, -85], [180, 85] ]

GeoJSON feature coordinates not displaying on OpenLayers map

I'm trying to display a GeoJSON polygon on a map. I've used the example provided by OpenLayers with the following data, but only the second polygon is displayed:
var geojsonObject = {
"type": "FeatureCollection",
"crs": {
"type": "name",
},
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[[103.92240800000013,21.69931],[100.93664,21.66959500000013],[108.031899,18.67076]]]
}
},
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[[-5e6, -1e6], [-4e6, 1e6], [-3e6, -1e6]]]
}
}
]
};
The code I'm using to parse and add the GeoJSON to the map is as follows:
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunction
});
I noticed different kinds of coordinates. In the second set the coordinates are represented like [-5e6, -1e6] with the e which I don't understand and in the first set - that don't work - they look like [103.92240800000013, 21.69931].
Is this a possible reason why my polygon is not displayed?
The problem is your two polygons are specified using different coordinate spaces and you need to determine which map projection you are going to use. By default OpenLayers uses something they call a "spherical mercator" and without delving into the detail the geometry coordinates are represented by pixels on a 2D plane.
Ideally, you would fix your GeoJSON to provide all coordinates in the same projection. If you can't do that, here is a working solution:
The set that you say aren't working look like longitude and latitude (GIS) coordinates and need to be transformed if they are to be displayed on the same layer - in the following example I've tagged the features that require transform using the GeoJSON properties like so:
var geojsonObject = {
type: 'FeatureCollection',
// ...
features: [
{
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [/* ... */],
properties: {
requiresTransform: true // <- custom property
}
}
},
// ...
]
};
Before adding features to the layer source you could then do something like the following:
var features = (new ol.format.GeoJSON()).readFeatures(geojsonObject);
features.forEach(function(feature){
if(!feature.get('requiresTransform'))
return; // ignore
var geometry = feature.getGeometry(),
coords = geometry.getCoordinates();
if(geometry instanceof ol.geom.Polygon)
geometry.setCoordinates(transformPolyCoords(coords));
});
function transformPolyCoords(/* Array */ a){
return a.map(function(aa){
return aa.map(function(coords){
return ol.proj.transform(coords, 'EPSG:4326', 'EPSG:3857');
});
});
}
There may be a cleaner way of managing this and I'd imagine it involves keeping the separate formats in separate GeoJSON objects and I don't know how close it is to what you were expecting, but this is what I came up with using what you provided » working example.

Google maps : pan to a center of a geojson route clicking on it

i´m new in google maps and after reading here and there I can´t make this work.
I´m doing a google map where Im showing bike forest routes using geojson ( linestring type, are given by coordinates points).
"type": "Feature",
"properties": {
"name": "larouco",
"color":"red"
},
"geometry": {
"type": "LineString",
"coordinates": [ [ -7.634432, 41.955357, 981.6 ], [ -7.635379, 41.954641, 896.1 ], [ -7.635824, 41.953955, 900.9 ] ................ ] }
All fine at the moment.
I need to pan the map to the center of the road when you clicks it.
map.data.loadGeoJson('http://myroutes.json');
map.data.setStyle(function(feature) {
var color = feature.getProperty('color');
return {
strokeColor: color,
strokeWeight: 3
};
});
map.data.addListener('mouseover', function(event) {
map.data.revertStyle();
map.data.overrideStyle(event.feature, {strokeWeight: 8});
});
map.data.addListener('mouseout', function(event) {
map.data.revertStyle();
});
here is where the problems starts
map.data.addListener('click', function(event) {
var center_rute = getCenter(new google.maps.LatLngBounds());
map.panTo(center_container);
//map.setZoom(13);
});
Thinks that LatLngBounds is the way but i´m running in circles...
Thanks,
Jul
You must access the geometry of the feature and create the LatLngBounds on your own by iterating over the points of the path(geometry)

Styling of Leaflet Features doesn't work

I've been trying to add a polygon on a Leaflet map and give it a style. I've been following their tutorials on http://leafletjs.com/examples/geojson.html however with no success.
My code is as following:
var myStyle = {
"color": "#0000FF",
"fill": true,
"opacity": 0.65
};
var myPolygon = [{
"type": "Feature",
"properties": {
"name": "Poly test",
"popupContent": "this is my test!",
},
"geometry": {
"type": "Polygon",
"coordinates": [[
[6.0, 52], // top right
[5.9, 52], // top left
[5.9, 51.5], // bottom left
[6.0, 51.5]
]]
}
}];
// Create a map with standard location
map = L.map('map').setView([52.2, 6.5], 9);
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osm = new L.TileLayer(osmUrl, {minZoom: 3, maxZoom: 14});
// Ask the user to get their current location
map.locate({setView : true});
// Add the tilelayer to the map
map.addLayer(osm);
L.geoJson(myPolygon, {
style: myStyle
}).addTo(map);
// Add event listeners
map.on('locationfound', myMarker);
The polygon outerlines are drawn, but with the standard blue color.
Could someone point me to the right solution on how to do this right?
Thanks!
You need fillColor and fillOpacity, see:
http://leafletjs.com/reference.html#path

Leaflet clear geojson layer (polyline)

I am a creating a polyline using a geojson. The format of my geojson is as below:
var myLines = [{
"type": "LineString",
"coordinates": [[-75, 21.9], [-75.4, 22.7], [-76.5, 23.4]]
}, {
"type": "LineString",
"coordinates": [[-105, 40], [-110, 45], [-115, 55]]
}];
L.geoJson(myLines).addTo(map);
I have a clear polyline function as below:
function clear_polyline(){
$.each(myLines, function(ind,poly){
map.removeLayer(poly);
});
}
This function does not clear the layer nor does it throw any error.
How do I clear a polyline in leaflet?
You need to remove the Leaflet layer from the map, not the GeoJSON object that the layer was created from. L.GeoJSON is a FeatureLayer that will contain all of the items in "myLines" so you should do something like this to remove it:
var linesFeatureLayer = L.geoJson(myLines);
linesFeatureLayer.addTo(map);
function clear_polyline() {
map.removeLayer( linesFeatureLayer );
}
var linesFeatureLayer = L.geoJson(myLines);
linesFeatureLayer.clearlayer()

Categories

Resources