I have a set of coordinates that I want to use them to draw a polygon with OpenLayers. The coordinates are the following:
[["50.12345","30.12345"],["40.12345","20.12345"],["60.12345","10.12345"],["70.12345","90.12345"]]
How can I draw a polygon with those coordinates? I'm trying the following but it doesn't seem to work:
var coords = "[["50.12345","30.12345"],["40.12345","20.12345"],["60.12345","10.12345"],["70.12345","90.12345"]]";
var polygon = new ol.geom.Polygon([coords]);
polygon.transform('ESPG:4326','ESPG:3857');
var feature = new ol.feature(polygon);
var vectorSource = new ol.source.Vector({});
vectorSource.addFeature(feature);
layer = new ol.layer.Vector({
source: vectorSource});
map.addLayer(layer);
Any ideas? Thanks!
// instead of this - a string
var coords = "[["50.12345","30.12345"],["40.12345","20.12345"],["60.12345","10.12345"],["70.12345","90.12345"]]";
// change to an array of arrays - remove the beginning quotes
var coords = [["50.12345","30.12345"],["40.12345","20.12345"],["60.12345","10.12345"],["70.12345","90.12345"]];
// and then you have to convert these string coordinates to number type
coords.map(function(coord){
return [parseFloat(coord[0]), parseFloat(coord[1])];
});
Proceed with the remainder - note that ol.Feature is written with capital letter.
Related
I would like to know how to calculate the centre of a polygon created with this code from Mapbox: https://www.mapbox.com/mapbox.js/example/v1.0.0/show-polygon-area/
I would like to place a marker on the centre of the polygon after it's been created.
Thanks in advance.
To calculate the center of a polygon you first need to get it's bounds, that can be done using the getBounds method of L.Polygon which it enherits from L.Polyline:
Returns the LatLngBounds of the polyline.
http://leafletjs.com/reference.html#polyline-getbounds
It returns a L.LatLngBounds object which has a getCenter method:
Returns the center point of the bounds
http://leafletjs.com/reference.html#latlngbounds-getcenter
It returns a L.LatLng object which you can use to create a L.Marker:
var polygon = new L.Polygon(coordinates).addTo(map);
var bounds = polygon.getBounds();
var center = bounds.getCenter();
var marker = new L.Marker(center).addTo(map);
Or you can shorthand it:
var polygon = new L.Polygon(coordinates).addTo(map);
var marker = new L.Marker(polygon.getBounds().getCenter()).addTo(map);
Using that in the Mapbox example would look something like this:
function showPolygonArea(e) {
featureGroup.clearLayers();
featureGroup.addLayer(e.layer);
// Here 'e.layer' holds the L.Polygon instance:
new L.Marker(e.layer.getBounds().getCenter()).addTo(featureGroup);
e.layer.bindPopup((LGeo.area(e.layer) / 1000000).toFixed(2) + ' km<sup>2</sup>');
e.layer.openPopup();
}
You can use turf library.turf.center(features) gives you a point feature at the absolute center point of all input features. where features in your case will be the polygon selected which you can get using mapboxDraw.getAll()
I have two JavaScript variables values comes from two text fields t1 and t2. When I pass values like:
var point=new ol.geometry.point(new ol.proj.transform([-81.9571,35.01],'4326','3857'));
Something like above works but not if I pass the variables. It points to wrong location. Like below code:
var point=new ol.geometry.point(new ol.proj.transform([t1,t2],'4326','3857'));
Make sure your coordinate value is not a string type:
var lon = parseFloat(t1);
var lat = parseFloat(t2);
Use a valid projection identifier:
var coord = ol.proj.transform([lon, lat], 'EPSG:4326', 'EPSG:3857');
All together:
var coord = ol.proj.transform([parseFloat(t1), parseFloat(t2)], 'EPSG:4326', 'EPSG:3857');
var point = new ol.geom.Point(coord);
I referred this post
How to determine if a point is inside a 2D convex polygon?
But I want to do the same in OSM with Open Layers.Please help me.
[Link](http://jsfiddle.net/Sanju5390/3tpLs6w3/)
You can do this with turf.js using turf.inside:
var polygon = new ol.Feature(new ol.geom.Polygon([[[-5e6, -1e6], [-4e6, 1e6],
[-3e6, -1e6], [-5e6, -1e6]]]));
var point = new ol.Feature(new ol.geom.Point([-4e6, 0e6]));
var format = new ol.format.GeoJSON();
var isInside = turf.inside(
format.writeFeatureObject(point),
format.writeFeatureObject(polygon));
console.log(isInside);
http://jsfiddle.net/d6o81vc7/22/
var map;
var vectors;
var point;
var drag;
Any long and Lat can be used
function mapCreate(lon,lat){
map = new OpenLayers.Map("map1");
var osm = new OpenLayers.Layer.OSM();
//create a vector
vectors = new OpenLayers.Layer.Vector("Vector Layer");
map.addLayer(osm);
var center = new OpenLayers.LonLat(lon,lat).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
Assign a lat long to the point
point = new OpenLayers.Geometry.Point(lat,lon);
Add point to vectors
vectors.addFeatures([new OpenLayers.Feature.Vector(point)]);
map.setCenter(center, 15);
//add vectors to map
map.addLayer(vectors);
}
Am I missing something?
Are you looking at the full map? There's a high chance that you're setting the point's location as lat/lon. The OpenLayers LonLat object is so named only to trick innocent users like you into thinking that it automatically converts latitude longitude, or expects them, or something. Don't trust it, reproject into the projection of your map.
I thought Collection were necessary, but looks like you have lat & lon swapped. A point must have lon, then lat.
feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Collection([new OpenLayers.Geometry.Point(0, 0)]), {});
vectors.addFeatures([feature]);
I have 2 OpenLayers.LonLat objects, and I want to determine the distance in pixels for the current zoom between the 2. I'm using OpenLayers.Layer.getViewPortPxFromLonLat() to determine the x and y of the points and then subtract to see the difference between the 2, but the values that I get are very small for points that are 2000km apart.
Here is my code:
var center_lonlat = new OpenLayers.LonLat(geometry.lon, geometry.lat);
var center_px = layer.getViewPortPxFromLonLat(center_lonlat);
var radius_m = parseFloat(feature.attributes["radius"]);
var radius_lonlat = OpenLayers.Util.destinationVincenty(center_lonlat, 0, radius_m);
var radius_px = layer.getViewPortPxFromLonLat(radius_lonlat);
var radius = radius_px.y - center_px.y;
I'm trying here to draw a circle, giving that I receive a center point and a radius in meters. The LonLat object seems to be ok.
Am I doing something wrong ?
I found the issue: destinationVincenty() need and returns coordinates in wgs84 where my map was using spherical mercator projection.
I hope I got correctly the answer, because projections make me dizzy and never really understood them :(. I was looking in the console to the numbers for my coordinates and the coordinates from the map.getExtent() that is used to calculate the getViewPortPxFromLonLat() and I realised they are not in the right order of magnitude, and then it hit me.
So, the code is now:
var spherical_mercator = new OpenLayers.Projection("EPSG:900913");
var wgs84 = new OpenLayers.Projection("EPSG:4326");
var map = feature.layer.map;
var geometry = feature.geometry;
var center_lonlat = new OpenLayers.LonLat(geometry.y, geometry.x);
var center_px = map.getViewPortPxFromLonLat(center_lonlat);
var radius_m = parseFloat(feature.attributes["radius"]);
var radius_lonlat = OpenLayers.Util.destinationVincenty(center_lonlat.clone().transform(spherical_mercator, wgs84), 0, radius_m).transform(wgs84, spherical_mercator);
var radius_px = map.getViewPortPxFromLonLat(radius_lonlat);
var radius = Math.abs(radius_px.y - center_px.y);
Measured the circles with the OpenLayers.Control.ScaleLine, and the size is dead on :D
You seem to be doing right. If the distance you get is too small, maybe there is a problem with OpenLayers.Util.destinationVincenty function? Have you tried to replace the bearing (0) with anything else - its value seem to be not important in your case. But frankly speaking, I wasn't able to understand how it works while browsing the source