center of a polygon created with mapbox - javascript

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()

Related

Draw a polygon using openLayers

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.

I have a polygon , and I know all of 4 points. How do I determine if a given point is inside the polygon with OpenLayers?

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/

Google Maps check if circle area is visible within map boundaries

I have a Google Map which contains a circle area.
I want to know if the circle is currently visible within the map's boundaries.
What I found so far is to check whether the center of the circle is within the boundaries, but I want to check for the whole circle and not only it's center.
My code that checks if the map's current center is within the boundaries of the circle is this:
google.maps.event.addListener(map, 'bounds_changed', function()
{
var circleBounds = circle.getBounds();
console.log(circleBounds.contains(map.getCenter()));
});
So what i want is something like this, which of course is not correct:
circleBounds.contains(map.getBounds());
Determine what the northmost, southmost, westmost, and eastmost LATLNGs of the circle are. You can find this given the circle radius
Determine if all points are inside the viewport bounds
If true, then yes, the circle must be viewable!
and you really should go back to your old questions and ACCEPT them (click on the check mark outline next to the best answer). This is how you show your appreciation for the hard work your answerers provided.
This is an old question - dinosaur-old in internet years - but if you're comparing two bounds, then the following holds a fortiori, n'est-ce pas?:
if(a.getBounds().contains(b.getBounds().getNorthEast())
&& a.getBounds().contains(b.getBounds().getSouthWest()))
{console.log('B is within A... Bounds are RECTANGLES: \
You only need to test two \
diagonally-opposing corners')};
That's because for a rectangle R, SW is (max(x),min(y)); NE is (min(x),max(y)) - and therefore all (x,y) in R are covered by the test.
I sure hope that's the case - it's how I do all my bounds comparisons...
Thanks Tina CG Hoehr.
Just in case anyone else wants this, here is the code for my question:
// Get the bounds
var circleBounds = circle.getBounds();
var ne = circleBounds.getNorthEast(); // LatLng of the north-east corner
var sw = circleBounds.getSouthWest();
var nw = new google.maps.LatLng(ne.lat(), sw.lng());
var se = new google.maps.LatLng(sw.lat(), ne.lng());
google.maps.event.addListener(map, 'bounds_changed', function()
{
var mapBounds = map.getBounds();
// Log whether the circle is inside or outside of the map bounds
if(mapBounds.contains(ne))
{
console.log("northeast is viewable");
}
if(mapBounds.contains(sw))
{
console.log("southwest is viewable");
}
if(mapBounds.contains(nw))
{
console.log("northwest is viewable");
}
if(mapBounds.contains(se))
{
console.log("southeast is viewable");
}
});

OpenStreetMap point not showing on map with open layers

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]);

google maps middle of a polyline (centroid?)

I have a list of polylines, just like google maps does when I click on the polyline I want an infowindow to show up just where I clicked, and it works just fine with this function
function mapsInfoWindow(polyline, content) {
google.maps.event.addListener(polyline, 'click', function(event) {
infowindow.content = content;
infowindow.position = event.latLng;
infowindow.open(map);
});
}
the problem comes when I click on the list(using the same function for that), event obviously doesn't have the latLng, but I'd like infowindow to show up in the middle of the polyline anyway, just like it does when you click on the list in the google maps link I mentioned before.
Tried LatLngBounds(); but that gives the actuall center of the area the polylines create, not the middle I need.
Any idea how to do it?
So this is the(bit hacky) solution.
Use http://www.geocodezip.com/scripts/v3_epoly.js library, then count the total length of you polyline(various ways), divide it in half and call epoly's .GetPointsAtDistance() function upon it.
This should return LatLng point, but it acts a bit weird sometimes, returning two points or even turning that point somehow "broken". So the most secure thing you can do is probably this:
var pointInHalf = polyline.GetPointsAtDistance(polylineLength);
var pointCoordinate = new google.maps.LatLng(pointInHalf[0].lat(), pointInHalf[0].lng());
Well, better than nothing.
From http://www.geocodezip.com/v3_polyline_example_geodesic_proj.html
Without extensions and assuming the polyline is a straight line.
It is possible to convert the lat/lng coordinates to point plane (x,y) postions and calculate the average between the two. This will give you a central pixel position. You can then convert this position back to a latlng for map plotting.
var startLatLng = startMarker.getPosition();
var endLatLng = endMarker.getPosition();
var startPoint = projection.fromLatLngToPoint(startLatLng);
var endPoint = projection.fromLatLngToPoint(endLatLng);
// Average
var midPoint = new google.maps.Point(
(startPoint.x + endPoint.x) / 2,
(startPoint.y + endPoint.y) / 2);
// Unproject
var midLatLng = projection.fromPointToLatLng(midPoint);
var midMarker = createMarker(midLatLng, "text");
More information on changing the projection http://code.google.com/apis/maps/documentation/javascript/reference.html#Projection
So firstly you need to use the geometry library which calculates distances. Add libraries=geometry to your JS call, e.g.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
Assuming you know the start point and end point for your polyline, you should be able to do this:
var inBetween = google.maps.geometry.spherical.interpolate(startLatlng, endLatlng, 0.5);
infowindow.position = inBetween;
I guess if you don't already know the start and end points, you could work it out from polyline.getPath().
to get the coordinates of your polyline you should do:
var widePath = new google.maps.Polyline({
path: waypointsCoordinates,
strokeColor: '#3366FF',
strokeOpacity: 0.0,
editable: true,
draggable: true,
strokeWeight: 3
});
and do:
var latLng [];
latLng = widePath.getPath().getArray();
Might be a bit old as well, but why not add the infobox on the click?
infowindow.setPosition(event.latLng);
infowindow.open(this.getMap());
If it's a click that is.

Categories

Resources