Leaflet: showing dynamic polylines together on a map using layers - javascript

I'm working on a task of showing all polylines(of different colours) on my map using leaflet. I'm getting all my dynamic polylines' latitudes and longitudes with their colours but when I merge it using layers, it just takes the last polyline and shows it.
I think I'm making some mistake in layering it. Can someone recommend the correct way to layer polylines in leaflets?
Here's a sample of the code where this is happening -
let newColour = this.returnMapColor(moment(startDate).day());
var layerGroups = {}
console.log("colour", newColour, startDate );
let range = this.props.history.filter((v) => { return moment(v.time).format("YYYY-MM-DD") == moment(startDate).format("YYYY-MM-DD") });
startDate = moment(startDate).add(1, 'days');
range.map((row)=> {
positions.push([row.latitude,row.longitude,row.sp] )
});
if(this.props.map){
const leafletMap = this.props.map.leafletElement;
this.hotlineLayer = L.layerGroup(L.polyline(positions, {color: newColour})).addTo(leafletMap);
}
++i;

A polyline requires at least two sets of lat, longs. Could you point out where in your code are you forming polylines?
In your code, the range.map the operation will only lead to creating an array of positions. And hence, your code is rendering a single line.
If you intend to create multiple polylines and render them using LayerGroup, I would suggest something in the lines of:
var latlngs1 = [
[45.51, -122.68,0],
[37.77, -122.43,1],
[34.04, -118.2,2]
];
var latlngs2 = [
[34.04, -118.2,2],
[32.08, -110.5,2]
];
const polyline1 = L.polyline(latlngs1, {color: 'red'})
var polyline2 = L.polyline(latlngs2, {color: 'blue'})
var hotlineLayer = L.layerGroup([polyline1, polyline2]).addTo(map);
Example Code: https://jsfiddle.net/idhruvs/n75omjbd/32/

Related

NDVI time series for polygons, not keeping in the geometry

I'm trying to calculate NDVI for a geometry. When the code is executed the images that are added to the map extend outside of the geometry area. I've tried for a week or so to fix it but with no luck. If anyone could help that would be great.
//Calculating NDVI for the period 2000-01-01 to 2001-01-01//
var ndvi_palette = ['FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901', '66A000', '529400','3E8601', '207401', '056201', '004C00', '023B01', '012E01', '011D01', '011301'];
function addNDVI(image){
var ndvi = image.normalizedDifference(['B4','B3']);
return image.addBands(ndvi);
}
var filtered = L7
.filterDate('2000-01-01','2001-01-01')
.filterBounds(geometry);
var with_ndvi = filtered.map(addNDVI);
var rgb_vis = {min:0,max:3, bands:['B3','B2','B1']};
Map.addLayer(filtered.median(),rgb_vis,'RGB Median');
var greenest = with_ndvi.qualityMosaic('nd');
//Map.addLayer(greenest,rgb_vis,'RGB Greenest Pixel');
Map.addLayer(with_ndvi.median(),{bands:'nd',min:-0.1,max:1,palette:ndvi_palette},'NDVI_2000-2001');
This is my imports
And here is the current outcome

How to clamp GeoJSON data format to terrain in Cesium Sandcastle?

I have terrain view in Cesium Sandcastle and I have loaded roads data in GeoJSON format, they are lines. I want to clamp them on terrain, like this example (in drop-down menu choose "Sample line positions and draw with depth test disabled") -> http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Ground%20Clamping.html&label=Tutorials
In the example, the line you see is defined within code, but I have data (roads) on my PC which is loaded in app. When loaded, roads are flat (under the terrain) and somehow I have to clamp them on terrain but don't know how.
I have tried using the existing code from the example but haven't succeed.
This is my code for now:
//Add terrain
var viewer = new Cesium.Viewer('cesiumContainer');
var cesiumTerrainProviderMeshes = new Cesium.CesiumTerrainProvider({
url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
requestWaterMask : true,
requestVertexNormals : true
});
viewer.terrainProvider = cesiumTerrainProviderMeshes;
viewer.scene.globe.depthTestAgainstTerrain = true;
//Load data (roads)
var dataSource = Cesium.GeoJsonDataSource.load('../../SampleData/ceste_rab_okvir.geojson');
viewer.dataSources.add(dataSource);
viewer.zoomTo(dataSource);
I know there is Cesium.GeoJsonDataSource.clampToGround, but as I'm not a developer, I don't understand how to write it in my code.
Does anyone knows how to do it? Or maybe there is another way to clamp roads to terrain?
Thanks in advance.
I've figured it out. It should be written like this:
//Add terrain
var viewer = new Cesium.Viewer('cesiumContainer');
var cesiumTerrainProviderMeshes = new Cesium.CesiumTerrainProvider({
url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
requestWaterMask : true,
requestVertexNormals : true
});
viewer.terrainProvider = cesiumTerrainProviderMeshes;
viewer.scene.globe.depthTestAgainstTerrain = true;
//Load data (roads)
Cesium.GeoJsonDataSource.clampToGround = true;
var dataSource = Cesium.GeoJsonDataSource.load('../../SampleData/ceste_rab_okvir.geojson');
viewer.dataSources.add(dataSource);
viewer.zoomTo(dataSource);

can't change marker icons / colors in mapbox

I'm manipulating the mapbox marker radius example here:
https://www.mapbox.com/mapbox.js/example/v1.0.0/marker-radius-search/
to attempt to change the color / icon of the markers within a certain radius of a random point, but the colors aren't changing despite the properties being registered as changed. Here's my code:
clusterLayer = L.mapbox.featureLayer('examples.map-h61e8o8e').on('ready', function(e) {
clusterGroup = new L.MarkerClusterGroup({
showCoverageOnHover: false,
animateAddingMarkers: true
});
e.target.eachLayer(function(layer) {
clusterGroup.addLayer(layer);
layerArray.push(layer);
});
map.addLayer(clusterGroup);
});
window.setTimeout(eventFunction,eventTiming);
function eventFunction(){
clusterLayer.setFilter(affectMarker);
}
function affectMarker(feature) {
var fLat = feature.geometry.coordinates[1];
var fLng = feature.geometry.coordinates[0];
var fPt = L.latLng(fLat,fLng);
var dist = eventPt.distanceTo(fPt);
if (dist < eventRadius){
feature.properties['marker-color'] = eventColorNegative;
feature.properties['marker-symbol'] = 'danger';
}
}
Why doesn't this work? I've verified that it is returning valid points.
Note also that the markers being used are MakiMarkers
I found two ways to do this, though neither, I think, is as ideal as being able to do so with the code above. The first is, rather than to use setFilter, use eachLayer:
clusterLayer.eachLayer(affectMarker);
and then in the loop, use setIcon:
layer.feature.properties['marker-color'] = eventColorNegative;
layer.feature.properties['marker-symbol'] = 'danger';
layer.setIcon(L.mapbox.marker.icon(layer.feature.properties));
The other way is to first include the MakiMarkers extension (which I believe has been deprecated and rolled into Mapbox):
https://github.com/jseppi/Leaflet.MakiMarkers
and then use this syntax:
layer.setIcon(L.MakiMarkers.icon({icon: "danger", color: eventColorNegative}));

How to display markers (huge numbers) on a map which has been logically divided into segments?

What i have done so far:
i'm developing an application where i have to display more than(50K) points/Markers on the Navteq map divided into different segments.
for example: if i have 50K points i will divide all points into different segments.
if i divide 50K points into 50 segments each segment would have 1000 points (may not be 50 segments , it may depend).
right now it is working but it takes long time and hangs to render all the points on the MAP.so that i would like to perform segmentation displaying to display only few points with clustering.
so that i can get an idea of how the segment will look like.
but the problem here is i should only perform the clustering based on the segments.otherwise points from different segments willbe mixed together and displayed
as single unit and that conveys the wrong information to the user.
so here my question is: is it possible to perform the clustering based on the segment. so that only points from same segment will be clustered.
Note: if this is not possible, i would like to use Latest version of here-maps 2.5.3 (Asynchronous) may reduce some time while loading, so that i would like to use indexing functionality also while rendering the points
to improve the rendering time using nokia.maps.clustering.Index class.
i studied that indexing would reduce the time while rendering the points/markers on map. does it help in my case? could anybody please suggest how to perform indexing ?
This is the code with which i'm displaying points on map:
function displayAllLightPoints(arrLightPointCoordinats, totalLightPoints,
selectedSegmentId, totalSegmentsCount,segmentColorcode)
{
var MyTheme1 = function () {
};
segmentColorcode = segmentColorcode.substring(2,segmentColorcode.length-1);
MyTheme1.prototype.getNoisePresentation = function (dataPoint) {
var markerLightPoint = new nokia.maps.map.Marker(dataPoint, {
icon: new nokia.maps.gfx.BitmapImage("..//Images//Lightpoint//" +
segmentColorcode + ".png"),
anchor: {
x: 12,
y: 12
}
});
return markerLightPoint;
};
MyTheme1.prototype.getClusterPresentation = function (data) {
var markerLightPoint = new
nokia.maps.map.StandardMarker(data.getBounds().getCenter(), {
icon: new nokia.maps.gfx.BitmapImage("..//Images//
Segment/" + segmentColorcode + ".png", null, 66, 65),
text: data.getSize(),
zIndex: 2,
anchor: {
x: 12,
y: 12
}
});
return markerLightPoint;
};
var ClusterProvider = nokia.maps.clustering.ClusterProvider,
theme = new MyTheme1(),
clusterProvider = new ClusterProvider(map, {
eps: 0.00000000001,
minPts: 1000000,
strategy: nokia.maps.clustering.ClusterProvider.
STRATEGY_DENSITY_BASED,
theme: theme,
dataPoints: []
});
var lightpointsDataSet1 = new Array();
for (var i = 0; i < totalLightPoints; i++) {
lightpointsDataSet1[i] = { latitude: arrLightPointCoordinats[i][0],
longitude: arrLightPointCoordinats[i][1], title:
'LightPoint ' + (i + 1) };
}
clusterProvider.addAll(lightpointsDataSet1);
clusterProvider.cluster();
}
To deal with a very large (50K+) data set , I would do all the heavy number crunching server side and send over a new JSON response whenever the map is updated. Something like the HTML page described here
The key section of the code is the ZoomObserver:
var zoomObserver = function (obj, key, newValue, oldValue) {
zoom = newValue;
if (zoom < 7)
{ zoom = 7;}
if (zoom > 16)
{ zoom = 16;}
// Define the XML filename to read that contains the marker data
placeMarkersOnMaps('http://api.maps.nokia.com/downloads/java-me/cluster/'+ zoom + '.xml'
+ '?lat1=' + map.getViewBounds().topLeft.latitude
+ '&lng1='+ map.getViewBounds().topLeft.longitude
+ '&lat2='+ map.getViewBounds().bottomRight.latitude
+ '&lng2='+ map.getViewBounds().bottomRight.longitude);
};
map.addObserver("zoomLevel", zoomObserver );
Where the REST service returns a "well-known" data format which can be used to add markers and clusters to the map.
Now assuming you have two massive data sets you could make two requests to different endpoints, or somehow distinguish which cluster of data belongs to which so that you would just be returning information of the form:
{latitude':51.761,'longitude':14.33128,'value':102091},
i.e. using the DataPoint standard (which means you could use a heat map as well.
Of course, what I'm not showing here is the back-end functionality to cluster in the first place - but this leaves the client (and the API) to do what it does best displaying data, not number crunching.

Integrate Google Map with Markers from HTTPrequest Javascript

Hi there I am Using appcelerator, and I want to integrate a map with an array of markers I am getting from a HTTPRequest...
I am effing lost, totally lost.
This is how the map looks like:
var mapview = Titanium.Map.createView({
mapType: Titanium.Map.STANDARD_TYPE,
region: {latitude:33.74511, longitude:-84.38993,
latitudeDelta:0.01, longitudeDelta:0.01},
animate:true,
regionFit:true,
userLocation:true,
annotations:[mountainView]
});
And I have the example of 1 marker hardcoded ...
var mountainView = Titanium.Map.createAnnotation({
latitude:37.390749,
longitude:-122.081651,
title:"Appcelerator Headquarters",
subtitle:'Mountain View, CA',
pincolor:Titanium.Map.ANNOTATION_RED,
animate:true,
leftButton: '../images/appcelerator_small.png',
myid:1 // CUSTOM ATTRIBUTE THAT IS PASSED INTO EVENT OBJECTS
});
So yo create the marker and in the annotations section you add it to the map, the thing here is that I am getting the markers from this:
var url = "http://myURLwithMyParameters";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this function is called when data is returned from the server and available for use
// this.responseText holds the raw text return of the message (used for text/JSON)
var result = this.responseText;
var xml = Ti.XML.parseString(result);
var items = xml.documentElement.getElementsByTagName("marker");
var name = xml.documentElement.getElementsByTagName("name");
var value = xml.documentElement.getElementsByTagName("address");
var data = [];
for (var i=0;i<items.length;i++) {
data.push({
name: items.item[i].getElementsByTagName("name")[0].textContent,
address: items.item[i].getElementsByTagName("address")[0].textContent
})
Does any one know how to integrate this?
I think I must build the map in the same function as the markers, but I've tried several options and haven't found ANY example of this in the web.
Any clue would be very appreciated.
Thank you in advance.
If all you have is an address, you'll need to forward geocode those addresses to get lat/long coordinates. Those coords are required to place annotations on the map. Check the docs at forwardGeocoder(). There's an example in the KitchenSink

Categories