How to set the coordinates for a polygon in openlayers? - coordinates

I am very new to OpenLayers and JavaScript, and I have the following problem.
I have an .csv table representing the coordinates of points I want to visualize them on a map using OpenLayers.
I have found the following example on the OpenLayers page,
https://openlayers.org/en/latest/examples/polygon-styles.html
However, I couldn't understand the representation of the coordinates there. More specifically, I didn't know what does the e mean in the coordinate [-5e6, 6e6] for example.
However, I tried to plot a simple square on my map using my coordinates, but it just giving me a point, in the center of the map, as following:
https://jsfiddle.net/api/post/library/pure/#&togetherjs=bD5bfPm7vz
So I don't know what's exactly is wrong, and what should I change? I think it's all in the way the coordinates are written, but not sure though.
And this is my code:
var styles = [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
}),
new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: 'orange'
})
}),
geometry: function(feature) {
// return the coordinates of the first ring of the polygon
var coordinates = feature.getGeometry().getCoordinates()[0];
return new ol.geom.MultiPoint(coordinates);
}
})
];
var geojsonObject = {
'type': 'FeatureCollection',
'crs': {
'type': 'name',
'properties': {
'name': 'EPSG:3857'
}
},
'features': [{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [[[-5e6, 6e6], [-5e6, 8e6], [-3e6, 8e6],
[-3e6, 6e6], [-5e6, 6e6]]]
}
}]
};
var source = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
var layer = new ol.layer.Vector({
source: source,
style: styles
});
var basic = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [basic, layer],
target: 'map',
view: new ol.View({
center: [0, 3000000],
zoom: 2
})
});

OK, I found the answer.
The following coordinates [-5e6, 6e6] is in X,Y format, and is based on the EPSG:3857 projection. XeY is equal to X * 10 ^ Y. Normally the openlayers use the EPSG:3857 projection, but in order to use the longitude/latitude coordinates format, we have to use the projection: EPSG:4326 projection, and we specify it clearly like: projection: 'EPSG:4326

Related

Leafletjs heatmap

Leaflet has a nice heatmap layer, but which I am finding difficulties to handle when zooming into the map.
I can set the data to have a radius of 0.1 and they look very nice when I have a zoom level of 8.
If a user zooms in to a level of, say 10, the map becomes entirely covered by the heatmap.
Also, if the user zooms out to level 6 the heatmap becomes invisible.
Can anyone, please, let me know how to scale the radius of data points of the heatmap, so as to obtain a similar effect to that of Google Maps Heatmap?
Thank you!
EDITED:
I used the heatmap from Patrick Wield heatmap.js
The code I used is as follows:
<script>
window.onload = function() {
var myData = {
max: 1000,
data: [
{lat: 50.32638, lng: 9.81727, count: 1},
{lat: 50.31009, lng: 9.57019, count: 1},
{lat: 50.31257, lng: 9.44102, count: 1},
]
};
var baseLayer = L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © CloudMade',
maxZoom: 18,
minZoom: 7
}
);
var cfg = {
"radius": .1,
"maxOpacity": 1,
"scaleRadius": true,
"useLocalExtrema": true,
latField: 'lat',
lngField: 'lng',
valueField: 'count'
};
var heatmapLayer = new HeatmapOverlay(cfg);
var map = new L.Map('map', {
center: new L.LatLng(50.339247, 9.902947),
zoom: 8,
layers: [baseLayer, heatmapLayer]
});
heatmapLayer.setData(myData);
layer = heatmapLayer;
};
</script>

how to smothly translate/animate updated positions of mapboxgl JS points layer symbols

i'm trying to figure out how to animate the update of this map layer so that points translate smoothly to new positions rather than simply appearing there. i have not found any useful starting points in the mpabox gl tutorials / examples and was wondering if there is a straightforward way to approach this. thanks
the code below fetches a geojson doc from an api once every 60 seconds and updates the map layer.
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/light-v10', // style URL
center: [-73.93, 40.73], // centroid of NYC
zoom: 11 // starting zoom
});
var url = '/api/v1/nyc/livemap';
map.on('load', function () {
var request = new XMLHttpRequest();
window.setInterval(function () {
// make a GET request to parse the GeoJSON at the url
request.open('GET', url, true);
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
// retrieve the JSON from the response
var json = JSON.parse(this.response);
map.getSource('observations').setData(json);
map.flyTo({
center: json.geometry.coordinates,
speed: 0.5
});
}
};
request.send();
}, 60000); // refresh every n milliseconds
map.addSource('observations', { type: 'geojson', data: url });
map.addLayer({
'id': 'buses',
'type': 'circle',
'source': 'observations',
'paint': {
'circle-radius': 3,
//'circle-color': '#0039A6'
'circle-color': [
'match',
['get', 'occupancy'],
'full',
'#e55e5e',
'standingAvailable',
'#FFFF00',
'seatsAvailable',
'#00FF00',
/* null */ '#87CEFA'
]
},
});
});
Mapbox GL JS doesn't contain any mechanism for animating data points from one location to another.
You could use Turf's along function to interpolate each point some proportion along the way from its previous location to its new location.

How to add Turf.js squareGrid layer to mapbox gl?

I am new to this and trying to add a grid layer, using Mapbox GL. Would appreciate some help.
var bbox = [-95, 30 ,-85, 40];
var cellSide = 50;
var options = {units: 'miles'};
var squareGrid = turf.squareGrid(bbox, cellSide, options);
What you have so far gives you a GeoJSON object that you can add to your map. Assuming you have a created a map (follow the getting started example), you now need to add a GeoJSON source, then a layer that renders it.
Something like
map.on('load', function() {
map.addSource('grid', {
'type': "geojson",
'data': squareGrid
});
map.addLayer({
'id': 'grid',
'type': 'line',
'source': 'grid',
'paint': {
'line-color': 'red',
}
});
});

mapbox-gl-js create a circle around a lat/lng?

I need to create a circle around a point where a user clicks. How would I do this? Every tutorial shows extracting a circle from a geojson source and not creating one. Need to be able to edit the radius as well.
Did you try something yourself? Following the mapbox examples you should be able to get an idea of how to build something like that.
You would need to do 3 things:
Create a source that holds the data
Create a layer of type "circle" for displaying the data as circles
On every click of the user, extract the "latitude, longitude" and add a point to your data list. Then display all of those points as a circle on the map.
This is an example of how I would have coded that: https://jsfiddle.net/andi_lo/495t0dx2/
Hope that helps you out
mapboxgl.accessToken = '####';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/light-v9', //stylesheet location
center: [-74.50, 40], // starting position
zoom: 9 // starting zoom
});
map.on('load', () => {
const points = turf.featureCollection([]);
// add data source to hold our data we want to display
map.addSource('circleData', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [],
},
});
// add a layer that displays the data
map.addLayer({
id: 'data',
type: 'circle',
source: 'circleData',
paint: {
'circle-color': '#00b7bf',
'circle-radius': 8,
'circle-stroke-width': 1,
'circle-stroke-color': '#333',
},
});
// on user click, extract the latitude / longitude, update our data source and display it on our map
map.on('click', (clickEvent) => {
const lngLat = new Array(clickEvent.lngLat.lng, clickEvent.lngLat.lat);
points.features.push(turf.point(lngLat));
map.getSource('circleData').setData(points);
});
});
#map {
height: 500px;
}
<div id="map"></div>

How to get the coordinates of a drawn box in OpenLayers?

I am a novice to OpenLayers, so sorry for an obvious (and perhaps dumb) question, for which I found different approaches for solutions, but none working. Tried this and that, a dozen different suggestions (here, here, here, here, here) but in vain.
Basically, I want to pass the coordinates of a drawn rectangle to another webservice. So, after having drawn the rectangle, it should spit me out the four corners of the bounding box.
What I have so far is the basic OL layers example for drawing a rectangle:
var source = new ol.source.Vector({wrapX: false});
vector = new ol.layer.Vector({
source: source,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0, 255, 0, 0.5)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vector
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
});
var draw; // global so we can remove it later
function addInteraction()
{
var value = 'Box';
if (value !== 'None')
{
var geometryFunction, maxPoints;
if (value === 'Square')
{
value = 'Circle';
geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
}
else if (value === 'Box')
{
value = 'LineString';
maxPoints = 2;
geometryFunction = function(coordinates, geometry)
{
if (!geometry)
{
geometry = new ol.geom.Polygon(null);
}
var start = coordinates[0];
var end = coordinates[1];
geometry.setCoordinates([
[start, [start[0], end[1]], end, [end[0], start[1]], start]
]);
return geometry;
};
}
draw = new ol.interaction.Draw({
source: source,
type: /** #type {ol.geom.GeometryType} */ (value),
geometryFunction: geometryFunction,
maxPoints: maxPoints
});
map.addInteraction(draw);
}
}
addInteraction();
Now, what comes next? What is a good way of extracting the bounding box?
Thanks for any hints!
You need to asign a listener to the draw interaction. Like so:
draw.on('drawend',function(e){
alert(e.feature.getGeometry().getExtent());
});
Here is a fiddle