How can you get coordinates of a country in Javascript? - 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.

Related

Issues displaying OpenWeatherMap with leaflet

I am practicing on a simple weather app using OWM. I am fetching the coordinates and pass them to a function to display a map using leaflet.
Here is my code
function drawMap(lat,lon){
const mymap = L.map('map').setView([lat, lon],3);
L.tileLayer(`https://tile.openweathermap.org/map/temp_new/3/1/1.png?appid=${apiKey}`).addTo(mymap);
}
My issues are :
-Zoom level is required by leaflet but it's also in the openweather URL so i don't know if i need to put the same or not
-in the url, i'm supposed to put x and y tile coordinates , I don't really understand the required X and Y values and the OWM API doc doesn't really elaborate on those.
Right now , using the values 3/6/1 for example, i get
The zoom is just the same tiles over and over and you can't make out anything so obviously I'm doing something wrong
Thanks
I don't really understand what you are describing but normaly you would set template strings in the Tile-Url that can are replaced by leaflet:
L.tileLayer(`https://tile.openweathermap.org/map/temp_new/{z}/{x}/{y}.png?appid=${apiKey}`).addTo(mymap);

Check if list of latitude, longitude are withing range

I'm having a problem
I would like to ask what the most efficient way is to check if latitude and longitude coordinates are inside a range (for example 100 meters) from a list of latitudes and longitude points.
For example I have this list of coordinates:
[[48.34483,51.16.24517],[48.484,16.2585],[48.361,51.87739419],[6.38477205,51.87745015],[48.3645,51.16.73167],[6.38391099,51.87755068],[48.3575,16.725],[6.38380232,51.87720004],[6.38376297,51.87708017],[6.38375183,51.87704018],[6.38373055,51.8769829]]
I would like somehow that all points that are in a specific range (100m for example),
to be somehow grouped.
Is there any way how I can indicate that for example from the above list:
[48.484,16.2585],[48.361,51.87739419] and [48.3575,16.725]
are in a radius of 100m ( distance between these points is less then 100m) and they should be groped
Sounds like a great question for a GIS professional; you could perhaps post on gis.stackexchange.com. Are you using a mapping technology where you already have access to an API? The functionality that you're looking for are referred to as geometric operations. I'd start by looking into geometry functions available in an API which calculate the distance between points. You could find the geometric center of all of the points, then request the geometry API to create a buffer around that point. Next, query if each point falls within that buffer.
Found a post which might help with finding the center of the points here:
How do I find the center of a number of geographic points?
Also found a post on stackexchange which sounds very similar to yours, only the post is in reference to ArcGIS and the Point Distance (Analysis) tool:
https://gis.stackexchange.com/q/91571/81346
Ideally you'd use a geospatial db for this, to avoid performance issues when dealing with increasing numbers of points. MySQL, Postgres etc all support geospatial functions.
But as you've tagged your question with javascript, I'll post a JS solution. There's an npm package called haversine - with it, you should be able to loop through each point and return the other points that are within 100m. Something like:
// bring in haversine from npm
var haversine = require("haversine");
// define the full list of points
var data = [
[48.34483,51.1624517],
[48.484,16.2585],
[48.361,51.87739419],
[6.38477205,51.87745015],
[48.3645,51.1673167],
[6.38391099,51.87755068],
[48.3575,16.725],
[6.38380232,51.87720004],
[6.38376297,51.87708017],
[6.38375183,51.87704018],
[6.38373055,51.8769829]
];
var points = data.map(point => new Object({latitude: point[0], longitude: point[1]}));
// var to store results in
var results = [];
// loop through the points
points.forEach((pair) => {
var nearby = points;
// filter the full list to those within 100m of pair
nearby.filter(point => haversine(pair, point, {unit: 'mile'}) <= 100);
results.push({
'point': pair,
'nearby': nearby
});
});
console.log(results);
Note: I corrected some of the points in your list, which had double decimals so weren't valid

Why these openlayers' feaures get wrong coordinates?

I have a bunch of markers stored in a mysql database in a table with these attributes id,longitude,latitude.
With an ajax query I get these rows and print to console and they're exactly equal to the ones in the db.
When I create my features with openlayers, with the longitude and latitude retrieved from the db and stored in javascript variables, I don't understand why the markers are placed to another place (they're supposed to be in Italy and they are under Africa).
The interesting thing is that if I manually insert the coordinates while creating the features they show in the right place.
Browsing the internet and trying to debug my code I found some clues.
First, it may be cause of how I store longitude and latitude in the db. I saw there's someone who says DECIMAL(10,8) for latitude and DECIMAL(11,8) for longitude but all of my coordinates are similar to lon: 9.728068 and lat: 44.106414 so i decided to use DECIMAL(7,6) for longitude and DECIMAL(8,6) for latitude.
Second, if I try to console.log the data retrieved from the db I get the right coordinates e.g. 9.728068 and 44.106414 but if I get the coordinates from the features after I created them I get different values.
For the manually inserted coordinates, I get the exact same values, but for the other one no.
Here's a snippet of my code. It's a for loop that in this case will cicle 2 times
var lon = r[i]["Sensor_longitude"]; //getting longitude from success response
var lat = r[i]["Sensor_latitude"]; //getting latitude from success response
console.log(lon); //first time 9.728068, second time 9.728368
console.log(lat); //first and second time 44.106414
//using retrieved coordinates to create the feature
var areaFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([lon,lat], 'EPSG:4326', 'EPSG:3857')),
name: sniffer_name
});
//trying to put manually the coordinates
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([9.728068,44.106414], 'EPSG:4326', 'EPSG:3857')),
name: sniffer_name
});
console.log(ol.proj.transform(areaFeature.getGeometry().getCoordinates(),'EPSG:3857','EPSG:4326'));
console.log(ol.proj.transform(iconFeature.getGeometry().getCoordinates(),'EPSG:3857','EPSG:4326'));
I have 2 entries in my db which have
lon:9.728068, lat:44.106414
lon:9.728368 ,lat:44.106414
so I will make 4 markers (areaFeature and iconFeature for each entry). areaFeature has the coordinates retrieved from db and iconFeature has coordinates inserted manually.
I expected the first half of logs to be 9.728068, 44.106414 and the second one to be 9.728368, 44.106414 but instead I get this:
9.728068 //correct
44.106414 //correct
[9.728068, -45.893585099999996] //[correct,wrong]
[9.728068, 44.106414] //[correct,correct]
9.728368 //correct
44.106414 //correct
[9.728367999999998, -45.893585099999996] //[wrong,wrong]
[9.728068, 44.106414] //[correct,correct]
As you can see latitude is nearly correct (don't know why it adds so many digits after the point) but it is negative and longitude in the first case is correct but in the second one it has other digits in addition.

Geo Lat/Lng normalize in Javascript

Hello I have the problem that i use leaflet and I dont boundbox the map.
Now if an user is drag the map and going out of the normal -180 to 180 lng or -90 to 90 lat my markers dont shown at the new location.
The marker will requested from an api I have written.
Where I use the boundbox coordinates. The problem now is, that I send something like:
lat_min:-23.563987128451217
lat_max:70.61261423801925
lon_min:-343.828125
lon_max:136.40625
to my script and I don't know how i can normalize the coordinates correct to pass the degrees.
EDIT 24.10.2016 01:33 UTC
My MySQL use between:
geolat: {
$between: [lat_min, lat_max]
},
geolon: {
$between: [lon_min, lon_max]
},
Thank you for your hints and tips.
Dude leaflet itself provides wrapLatLng which can be used as map.wrapLatLng(latLngPoint), this returns normalized form of latitude longitude how we need.

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