Center of Polygon Google Maps JavaScript API v3 - javascript

I looked through this thread: How to get the center of a polygon in google maps v3?, and Matthew Scharley's answer currently marked as correct does not do it for me. I am downloading corner coordinates for 50-100 polygons dynamically from the server in an array of lat/long objects, and I need a dynamic not manual solution for determining polygon centers. The answer from the same thread by furiozo comes close to fulfilling my needs, as it calculates the average center of the polygon, but the results that I see in my console.log from his function:
google.maps.Polygon.prototype.my_getBounds=function(){
var bounds = new google.maps.LatLngBounds()
this.getPath().forEach(function(element,index){bounds.extend(element)})
return bounds
}
console.log(myPolygon.my_getBounds().getCenter());
are not something that I can readily use in my program.
What I get in the console is this:
_.M {}
lat: function ()
arguments: (...)
caller: (...)
length: 0
name: ""
prototype: Object
__proto__: function ()
<function scope>
Closure
a: 45.256705626
b: -75.91270512
Closure
Global: Window
lng: function() -- contains same sub-levels as lat: function() --
__proto__: Object
What I really need right now is how to get to the a & b lat/lng values that sit under the first Closure level in in lat: function() in the object I'm getting in my console. (I have checked manually by substituting these results in code, they represent the correct center for the first of my polygons). Any help with how to get to them will be greatly appreciated.
Or, if anybody knows of any up-to-date solution for how to get average polygon center coordinate values dynamically so that the end result will be in the format of (lat, lng), this may save my day.
Thank you very much!

What you're seeing is a LatLng object.
What you can do is simply call the lat() and lng() functions on it:
var lat = myPolygon.my_getBounds().getCenter().lat();
var lng = myPolygon.my_getBounds().getCenter().lng();

Related

HERE Maps API for Javascript : how to get boundaries longitude and latitude from current zoom Visible Map

I am using the HERE Maps API for Javascript for the webpage: how to get boundaries longitude and latitude from current zoom Visible Map.
When the map display on the webpage is a rectangle shape, what is the method to get 4 boundaries points longitude and latitude in the visible area of Here maps?
Many thanks
As per the documentation, the bounds object in getLookAtData method for ViewModel is a bounding box in 2D map and a polygon in 3D map. Therefore:
bb = map.getViewModel().getLookAtData().bounds.getBoundingBox();
bb.getTop();
bb.getLeft();
bb.getBottom();
bb.getRight();
// or
bb.getTopLeft();
bb.getBottomRight();
It's much more complicated than it should be:
map.getViewModel().getLookAtData().bounds.getBoundingBox()
You'll get an object like that:
Object {
ba: 12.375232332750691,
ga: 12.379826130043003,
ja: 51.33821375191854,
ka: 51.337248429832854,
b: null, a: null, c: null
}

How can you get coordinates of a country in Javascript?

I am making a react native app which includes a map and want to place markers at the centres of different countries. However to create each marker you must provide a set of coordinates so I need a function to which I can pass a country name and it returns the coordinates for somewhere in that country (either of its centre or its capital would be good).
getCoords = (country_name) => {
return coords {
latitude: lat_of_country_centre
longitude: long_of_country_centre
}
}
Does anyone know of a function or api that does this?
You would want to use a geocoding API like OpenCageData to convert a country name into a country.
For example, using OpenCageData, the request https://api.opencagedata.com/geocode/v1/json?key=YOUR_KEY&q=Germany would return a JSON object which contains various information about that location name.
In this case, the coordinates would be located at the path in the JSON object results[0].annotations.DMS, which contains lat and lng, latitude and longitude coordinates in degrees, minutes, and seconds (e.g.) 51° 5' 0.31056'' N for latitude and 10° 25' 24.40884'' E for longitude.
Experimentation with this API or others like it may help you find data that is the best for your specific application.
I would take a look at the Google Maps API. That’ll give you a good starting point.
you can take data from google i.e lat and long coords.
and load to your spreadsheet and write a simple program and load this into the array.

OpenLayers 3: Zoom map to coordinates in array

I need to zoom my OpenLayers map (which uses a Google Maps baselayer) to fit all of a given list of coordinates into the view.
I've stored the coordinates in an array of longitude and latitude pairs named pointsDecimal which looks like this:
pointsDecimal: Array[50]
0: 148.77638
1: -34.491728
2: 148.77896
3: -34.492302
4: 148.778090711323
...
Even-numbered indices (0, 2, 4 etc) are longitude, and odd-numbered indices (1, 3, 5 etc) are latitude.
This is the code I'm trying to use:
map.getView().fit(pointsDecimal, map.getSize());
But for some reason this puts me at maximum zoom level at the coordinates [0,0] - in the Gulf of Guinea, not in southeastern New South Wales where I'd like to be!
I know this would be much easier if I was using an OpenLayers source (e.g. source.getExtent()) in place of my pointsDecimal array, but this is not an option in this case for reasons I won't go into right now - I can only use the array.
Can anyone give me any hints please?
EDIT: I think I'm nearly there, thanks to Anupam. This is what I have now:
var extent = [pointsLongMin,pointsLatMin,pointsLongMax,pointsLatMax];
map.getView().fit(extent,map.getSize());
The values I'm passing to the array are as follows:
pointsLongMin: 148.771162
pointsLatMin: -34.5029736405108
pointsLongMax: 148.77896
pointsLatMax: -34.491728
But I'm still getting dumped out in the ocean at [0,0]. What am I doing wrong here?
In order to use map.getView().fit(extent,size).
extent denotes four points as [minx, miny, maxx,maxy].
It is actually a rectangle. try
var extent=[148.77638,-34.491728,148.77896,-34.492302];
map.getView().fit(extent,map.getSize());
most propable reason is that your map is projected on EPSG:3857while your extent EPSG:4326. So you need to transform your extent to your map projection.
var coordMin = ol.proj.fromLonLat([148.77638,-34.491728], 'EPSG:3857');
var coordMax = ol.proj.fromLonLat([148.77896,-34.492302], 'EPSG:3857');
var extent=[coordMin[0],coordMin[1],coordMax[0],coordMax[1]];
map.getView().fit(extent,map.getSize());
You may find a more elegand way to do the extent transformation. Unless you provide your full code we can only guess what is your map projection. I am just guessing is EPSG:3857 cause thats the default ol3 use.

mapbox fit bounds to country

i just want fit my map to my country. I saw some example from https://www.mapbox.com/mapbox-gl-js/example/fitbounds/ and it's fit to whole Kenya. It's a simple code but i don't know why this function takes two lat and longs. I just google it for what is Keyna lat and long? it's 1.2667° S, 36.8000° E. Why this is different than google's result.
function fit() {
map.fitBounds([[
32.958984,
-5.353521
], [
43.50585,
5.615985
]]);
}
How to fit to my specific area just like this.
If i search for the bounding box of Kenya, i find the following:
http://isithackday.com/geoplanet-explorer/index.php?woeid=23424863
Using those coordinates, it's looks ok:
map.fitBounds([
[-4.71712, 33.90884], // Northeast
[4.62933, 41.899059] // Southwest
]);
Example using Leaflet on Plunker: http://plnkr.co/edit/yRuTxjmQxcoqkVyFbE4q?p=preview
.fitBounds takes two latlng arguments, one for the upper-left corner of the mapview and one for the lower-right corner.
If you would like to just center the map on Kenya, you could use:
map.flyTo({center: [Lat, Lng]})
I also was looking for the answer on this question. Leaflet, for example, has a property of a layer to get its bounds (e.g.,map.fitBounds(layer.getBounds());). Mapbox GL doesn't have anything like that. At least not that I know. To handle this you may access the first and the last coordinates of the currently selected feature: map.fitBounds([feature.geometry.coordinates[0], feature.geometry.coordinates[feature.geometry.coordinates.length-1]]).
Here is the whole piece of code in case you want to have a popup with a Zoom button on it:
map.on('click', function (e) {
map.featuresAt(e.point, {layer: 'route-lines', radius: 10, includeGeometry: true}, function (err, features) {
if (err || !features.length)
return;
var feature=features[0];
new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML(popupTemplate)
.addTo(map);
var buttonZoomFeature = document.getElementById('button-zoom');
buttonZoomFeature.addEventListener('click', function (e) {
map.fitBounds([feature.geometry.coordinates[0], feature.geometry.coordinates[feature.geometry.coordinates.length-1]]);
});
});
});
var popupTemplate = '<div id="popup-div">\
<button id="button-zoom" class="button-zoom" type="button">Zoom to</button>\
</br>\
</div>';
PS. This approach works fine when the layer is a number of lines (roads, for example). If you want to fit the bounds to a country, which is a polygon, you may try taking the first longitude-latitude point as the one that has min latitude and for the second point the one that has max longitude. Or something like that. Just try to play around with this approach. I am sure it will work out.

Leaflet.js - Fit geoJSON co-ordinates on map view

I have a leaflet.js map that has points and linestrings on it that come from an external JSON file.
If I add:
map.setView(new L.LatLng(0,0), 10);
It will centre the map on the latitude and longitude 0,0. How can I set it so the map centre and zoom fit all of the points from the JSON on it?
You could add all of your layers to a FeatureGroup which has a getBounds method. So you should be able to just say myMap.fitBounds(myFeatureGroup.getBounds());
The getBounds method for L.FeatureGroup is only available in the master branch (not the latest version, 0.3.1), for now at least.
Similar case with me. I drawn all the markers from GeoJson data. So I written the function, which gets called repeatedly on button click. Just try if it suits your requirements.
function bestFitZoom()
{
// declaring the group variable
var group = new L.featureGroup;
// map._layers gives all the layers of the map including main container
// so looping in all those layers filtering those having feature
$.each(map._layers, function(ml){
// here we can be more specific to feature for point, line etc.
if(map._layers[].feature)
{
group.addLayer(this)
}
})
map.fitBounds(group.getBounds());
}
The best use of writing this function is that even state of map/markers changed, it will get latest/current state of markers/layers. Whenever this method gets called all the layers will be visible to modest zoom level.
I needed to do this when showing a user directions from his origin to a destination. I store my list of directions in an array of L.LatLng called directionLatLngs then you can simply call
map.fitBounds(directionLatLngs);
This works because map.fitBounds takes a L.LatLngBounds object which is just an array of L.LatLng
http://leafletjs.com/reference.html#latlngbounds

Categories