Point in Polygon using leaflet-pip - javascript

I'm trying to, given a .json containing a lot of points, determine how many there are in each region (probably returning a dictionary), which are defined in another .json file.
I'm doing this based on this example:
https://www.mapbox.com/mapbox.js/example/v1.0.0/point-in-polygon/
However, I can't get it to work.
This line:
var layer = leafletPip.pointInLayer(this.getLatLng(), states, true);
Returns empty for my test case.
Here is a jsfiddle reproducing my code:
http://jsfiddle.net/Pe5xU/346/
map = L.map('map').setView([40.658528, -73.952551], 10);
// Load a tile layer
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap',
maxZoom: 18,
minZoom: 10
}).addTo(map);
geojson = L.geoJson(data).addTo(map);
var all_markers = [];
var layers = {};
$.each(dots, function(index, rec) {
var markers = {}
if (rec.hasOwnProperty("latitude") && rec.hasOwnProperty("longitude")) {
var marker = L.circleMarker([rec.latitude, rec.longitude], marker_style()).addTo(map);
all_markers.push(marker);
}
});
var all_layers = L.featureGroup(all_markers);
map.fitBounds(all_layers.getBounds());
function marker_style() {
return {
radius: 4,
weight: 0,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
};
}
$.each(dots, function(index, rec) {
if (rec.hasOwnProperty("latitude") && rec.hasOwnProperty("longitude")) {
var layer = leafletPip.pointInLayer([rec.latitude, rec.longitude], geojson, true);
console.log(layer);
}
});

This code example provides coordinates in latitude, longitude order. As documented in the leaflet-pip readme, leaflet-pip expects coordinates in longitude, latitude order, the same as GeoJSON and other geospatial formats.

Related

Displaying orbits on ground track map using TLE lines

I am trying to draw an orbit on a ground track map using TLE lines like this using JS:
1 45657U 20035A 20196.59974008 .38210219 12083-4 47903-3 0 9997
2 45657 53.0001 319.7129 0028054 181.2741 293.9291 16.46735707 7405
var attribution =
'Map data © OpenStreetMap contributors';
var tile = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
var tle_Pos = getPosVel();
var longitude = tle_Pos.longitude
var latitude = tle_Pos.latitude
var worldMap = drawMap();
var objectDrawer = drawObject();
function getPosVel(){
var tleLine1 = '1 45657U 20035A 20196.59974008 .38210219 12083-4 47903-3 0 9997',
tleLine2 = '2 45657 53.0001 319.7129 0028054 181.2741 293.9291 16.46735707 7405';
var gmst = satellite.gstime(new Date());
var satrec = satellite.twoline2satrec(tleLine1, tleLine2);
var positionAndVelocity = satellite.propagate(satrec, new Date());
var gmst = satellite.gstime(new Date());
var geodeticCoords = satellite.eciToGeodetic(positionAndVelocity.position, gmst);
console.log(geodeticCoords);
return geodeticCoords
}
function drawMap() {
var map = L.map("mapid").setView([0, 0], 4);
L.tileLayer(tile, {
maxZoom: 25,
minZoom: 1.8,
attribution: attribution
}).addTo(map);
return map;
}
function drawObject() {
return L.marker([longitude, latitude]).addTo(worldMap);
}
I have tried to use satellite.js and Leaflet map but I ran into couple of problems doing this, First thing I cant figure how to predict and draw the orbit and not only the object's current latitude and longitude, Secondly, when I provide the TLE lines below it doesnt work at all, and when I provided the regular ISS TLE lines it worked but I dont think the latitude and longitude are accurate at all.
Is there anything alternative to use other than satellite.js or is there a right way to draw the full orbit of the TLE lines?
EXTRA: Here is an image of how I want the map to look like.

Change color of leaflet markers in realtime with websockets

I have the following code which polls my geoJSON /stations endpoint every 15 seconds and updates the map with a new layer of point features. It currently flickers during the update.
var map = L.map("mapid").setView([0,0], 1);
///////////////////////////
// Map Vector Tile Layer //
///////////////////////////
L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors',
maxZoom: 18,
}).addTo(map);
//////////////////
// Points Layer //
//////////////////
function onEachFeaturePoint (feature, layer) {
var html = `
<div>
<table class='table table-condensed table-striped'>
<tbody>
<tr>
<td>Station Name: ${feature.properties.name}</td>
</tr>
<tr>
<td>Latitude: ${feature.geometry.coordinates[1].toFixed(7)}</td>
</tr>
<tr>
<td>Longitude: ${feature.geometry.coordinates[0].toFixed(7)}</td>
</tr>
<tr>
<td>Height: ${feature.properties.height.toFixed(3)}</td>
</tr>
</tbody>
</table>
</div>
`;
layer.on(
'click',
function () {
document.getElementById('station-info').innerHTML = "";
document.getElementById('station-info').innerHTML = html;
}
);
/*layer.bindPopup(html);*/
}
function markerOptions (feature) {
var rnum = Math.floor(Math.random()*10);
if ( rnum < 5 ) {
return { radius: 4, fillColor: "#ff0000", color: "#000", weight: 1, opacity: 1,fillOpacity: 0.8 };
}
return { radius: 4, fillColor: "#00ff00", color: "#000", weight: 1, opacity: 1,fillOpacity: 0.8 };
}
function pointToLayer (feature, latlng) {
return L.circleMarker(latlng, markerOptions(feature));
}
function addStations() {
map.eachLayer(function(layer) {
if (layer.hasOwnProperty("points")) {
map.removeLayer(layer);
}
});
var stationsLayer = new L.GeoJSON.AJAX(
"/stations",
{
onEachFeature: onEachFeaturePoint,
pointToLayer: pointToLayer,
}
);
stationsLayer.points = true;
// Add the layer
stationsLayer.addTo(map);
setTimeout(addStations, 15000);
}
addStations();
Ultimately I'd like to use data arriving from a websocket to update the map.
var loc = window.location;
var uri = 'ws:';
if (loc.protocol === 'https:') {
uri = 'wss:';
}
uri += '//' + loc.host;
uri += loc.pathname + '/' + 'stream';
ws = new WebSocket(uri)
ws.onopen = function() {
console.log('Connected')
}
ws.onmessage = function(evt) {
// do something here to update color of the stations
}
I was looking into using combining d3.js with leaflet (https://bost.ocks.org/mike/leaflet/), or possibly leaflet's domUtil.addClass() method (How to make markers in Leaflet blinking). But examples often show updating a single point. I've gotten a little lost when trying to extrapolate that to multiple points (e.g. a geoJSON feature collection).
Is there a better way to update the color of 100s of points on a map in real-time without replacing the entire layer?

How in leaflet add custom data to polyline?

In jquery 3/leaflet / turf app
I use custom class extended from CircleMarker
as I need in any marker keep info about any point and info on nearby points.
Markers are connected with polylines and I want to keep simialr information polyline
and clicking on it get this info. I failed to make it. I do
customCircleMarker = L.CircleMarker.extend({
options: {
first_market: false,
last_market: false,
point_id: null,
prior_point_id: null,
}
});
var selectedPoint= {}
var points = [
{id: 1, title:'title #1 ', lat:52.509, lng:-3.08},
{id: 2, title:'title #2 ', lat:51.503, lng:-1.06},
{id: 3, title:'title #3 ', lat:49.51, lng:-2.47}
];
var mymap = L.map('mapid').setView([51.505, -0.09], 7);
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, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1
}).addTo(mymap);
drawPoints()
function drawPoints() {
let polylinePoints= [] // I get all info about all Polylines
let loop_index = 0
points.forEach(point => {
let priorPoint= null
if(loop_index > 0) {
priorPoint= points[loop_index - 1]
}
var myMarker = new customCircleMarker([point.lat, point.lng], {
title: 'unselected',
radius: 20,
first_market: loop_index == 0,
last_market: loop_index == points.length-1,
point_id: point.id,
prior_point_id: priorPoint ? priorPoint.id : null,
});
myMarker.on('click', function (event) { // THAT WORKS OK
console.log('myMarker.event.target.options.point_id::')
console.log(event.target.options.point_id)
});
myMarker.addTo(mymap);
polylinePoints[polylinePoints.length]=[point.lat, point.lng]
loop_index++
})
var radius = 10;
var polyline = new L.Polyline(polylinePoints, {
color: 'green',
opacity: 1,
weight: 2,
customData:{ // BUT TAT DOES NOT WORK AS POINT IS OUT OF LOOP
point_id: point.id,
prior_point_id: priorPoint ? priorPoint.id : null,
}
// offset: radius
});
// Add click listener
polyline.on('click', function (event) {
event.originalEvent.stopPropagation();
window.event.cancelBubble = true; // CAN NOT STOP Propagation
showModal(event)
// alert('Polyline clicked!');
});
// Add polyline to featuregroup
polyline.addTo(mymap);
// zoom the map to the polyline
mymap.fitBounds(polyline.getBounds());
} // function drawPoints () {
How can I add custom data to polyline ?
Thanks!
You don't have to extend the CircleMarker class to add more options. You can do this at the default way:
var myMarker = L.circleMarker([point.lat, point.lng], {
title: 'unselected',
radius: 20,
first_market: loop_index == 0,
last_market: loop_index == points.length-1,
point_id: point.id,
prior_point_id: priorPoint ? priorPoint.id : null,
});
Also don't use polylinePoints[polylinePoints.length]= if it is not necessary. Use polylinePoints.push(
What do you want with the data on the polyline? Why you not adding the whole point array to the polyline?
var polyline = new L.Polyline(polylinePoints, {
customData:{
points: points
}
});
Else you can create a array of the point ids:
let polylinePoints= [] // I get all info about all Polylines
let loop_index = 0;
let pointIds = [];
points.forEach(point => {
pointIds.push(point.id);
//...
var polyline = new L.Polyline(polylinePoints, {
customData:{
points: pointIds
}
});
Or (what I recommand) to add the markers to the polyline:
let markersForPoly = [];
points.forEach(point => {
//... Loop ...
myMarker.addTo(mymap);
markersForPoly .push(myMarker);
});
//.. Code
var polyline = new L.Polyline(polylinePoints, {
customData:{
points: markersForPoly
}
});
And the you can get the points in the click listener:
polyline.on('click', function (event) {
var layer = event.target;
var points = layer.options.customData.points;
console.log(points);
});
Example
https://jsfiddle.net/falkedesign/61sjx3bv/

Longitude and Latitude of polyline : Leaflet

Is their a way to get latitude and longitude of polyline?
var firstpolyline = new L.Polyline(pointList, {
color: 'black',
opacity: 5,
smoothFactor: 1,
weight: 3,
})
map.addLayer(firstpolyline);
firstpolyline.getLatLng();
here firstpolyline is givng an error that "getLatLng() is not a function". I want to check if polyline is within the map bound or not like this
var bounds = map.getBounds();
if(bounds.contains(firstpolyline.getLatLng())){
......
}
You have to use getLatLngs() function. So try this:
var firstpolyline = new L.Polyline(pointList, {
color: 'black',
opacity: 5,
smoothFactor: 1,
weight: 3,
})
map.addLayer(firstpolyline);
var arrayOfPoints = firstpolyline.getLatLngs();
Then you can easily iterate over an array of points and get latitude and logitude or check if point is in bounds of polygon.
for(var i=0; i < arrayOfPoints.length; i++) {
if(map.getBounds().contains(arrayOfPoints[i])) {
console.log('is in bounds');
};
}

How to draw polyline in nokia here map using json of lat long in javascript

i am new in using nokia here map, how i can plot json of lat long in nokia here map without marker but it draw polyline..
Here is my code:
$.each(data, function(i, val){
var coord = new nokia.maps.geo.Coordinate(parseFloat(val.latitude),parseFloat(val.longitude));
var markerPolyline = new MarkerPolyline(
coord,
{
polyline: { pen: { strokeColor: "#00F8", lineWidth: 4 } }
}
);
map.objects.add(markerPolyline);
});
I hope you can give some answer.. thanks in advance :)
these are the steps you should follow
1.-Create an array of coordinate objects.
2.-assign those coordinates to the new instance of the polyline
3.-add new polyline to map
example:
var aoCoordinates = []
$(data).each(function(i,val){
var latitude = parseFloat(val.latitude);
var longitude = parseFloat(val.longitude);
//create coordinate object
var coord = new nokia.maps.geo.Coordinate(latitude,longitude);
//add to array
aoCoordinates.push(coord);
})
//after the loop ends create instance of polyline
var markerPolyline = new MarkerPolyline(
aoCoordinates,
{
polyline: { pen: { strokeColor: "#00F8", lineWidth: 4 } },
marker: { brush: { color: "#1080dd" } }
}
);
map.objects.add(markerPolyline);
there are more examples in Nokias Developer page http://developer.here.com/javascript-apis/api-explorer

Categories

Resources