Get country from latitude longitude - javascript

I would like to know how I can get the country name from latitude & longitude using JavaScript. I am open to use of Google Maps’ JavaScript API. Can I also get city and zip?
Edit: My aim is to fill up the address field automatically, not to display it on a map.

I don't know if it works with google maps, but there is a web service that returns a country code and takes as parameters the lat and long.
Here is an example:
http://api.geonames.org/countryCodeJSON?lat=49.03&lng=10.2&username=demo
Returns a JSON data:
{"languages":"de","distance":"0","countryCode":"DE","countryName":"Germany"}
I also found a little description:
The iso country code of any given point.
Webservice Type: REST
Url: ws.geonames.org/countryCode?
Parameters: lat, lng, type, lang, radius (buffer in km for closest country in coastal areas)
Result: returns the iso country code for the given latitude/longitude
With the parameter type=xml this service returns an xml document with iso country code and country name. The optional parameter lang can be used to specify the language the country name should be in. JSON output is produced with type=JSON
See the docs
Edit: Please note that demo is just a demonstration user and you should create a user account at http://www.geonames.org/login in order to use the service.

Google Geocoding API provides these results in JSON format. It has a free tier but you will need to pay for unlimited requests to the API.
The API link to the request will look like this:
'https://maps.googleapis.com/maps/api/geocode/json?latlng=11.2742848,75.8013801&key=YOUR_API_KEY_HERE'

If a self-contained library (i.e. no server / internet connection, and fast) is desirable, and only country information is required, the following library based on openstreetmap data can be useful - https://github.com/hlaw/codegrid-js
<script type="text/javascript" src="[path]/codegrid.js"></script>
grid = codegrid.CodeGrid(); // initialize
grid.getCode (lat, lng, function (err, code) { ... });
The callback is called with code, the country code for the latlng.

<form id="form1" runat="server">
<div>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
<br />Country Code:
<script type="text/javascript">document.write(geoip_country_code());</script>
<br />Country Name:
<script type="text/javascript">document.write(geoip_country_name());</script>
<br />City:
<script type="text/javascript">document.write(geoip_city());</script>
<br />Region:
<script type="text/javascript">document.write(geoip_region());</script>
<br />Region Name:
<script type="text/javascript">document.write(geoip_region_name());</script>
<br />Latitude:
<script type="text/javascript">document.write(geoip_latitude());</script>
<br />Longitude:
<script type="text/javascript">document.write(geoip_longitude());</script>
<br />Postal Code:
<script type="text/javascript">document.write(geoip_postal_code());</script>
</div>
</form>

Yes, you can use google maps to find the country for given latitudes and longitudes. Use the reverse geocoding service.
You can get the country, city, zip code and the complete address from the response you get from the server. Check the example from the link for details ;)

If you are using golang you can use one of these 2 libraries to get the country and you don't need to even need make an api call as the data set is inbuilt so its unlimited.
https://github.com/SocialHarvest/geobed
https://github.com/bradfitz/latlong

You can do it with: https://www.weatherapi.com/ its FREE.
My demo is in React and step by step, but you can do it in any way you want, the key is this Weather API, that accepts LON and LAT as a string to produce city and weather info ->
https://api.weatherapi.com/v1/forecast.json?key=YOUR-KEY&q=LATITUDE,LONGITUDE&days=1&aqi=no&alerts=n
Note: you will to generate YOUR OWN KEY, by signing up
You will need 4 states for this:
const [userAllowedLocation, setUserAllowedLocation] = useState(true);
const [latitude, setLatitude] = useState("");
const [longitude, setLongitude] = useState("");
const [city, setCity] = useState("");
get Lat and Lon + pop up
First: Request access to 'location' from user (this will have a POP-UP), by using this code and set state to Latitude and Longitude.
useEffect(() => {
function getPosition() {
const successCallback = (position) => {
console.log(position);
setLatitude(position.coords.latitude);
setLongitude(position.coords.longitude);
setUserAllowedLocation(true);
};
const errorCallback = (error) => {
setUserAllowedLocation(false);
console.log(error);
};
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
}
getPosition();
}, []);
Fetch City / Country based on Lat & Lon:
Second use https://www.weatherapi.com/ API to get City and other intel, based on Lat and Lon
API looks like this: https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=53.3498053,-6.2603097&days=1&aqi=no&alerts=n
API with explanation: https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=LATITUDE,LONGITUDE&days=1&aqi=no&alerts=n
Now call this API with latitude and longitude to get location data, including city. I am using useEffect as a trigger, so as soon as I get info on Latitude I call the api using axios and set City state to what ever comes out of the api object.
useEffect(() => {
if (latitude === "" || longitude === "") { // this is to stop fetching data on component mount, cause we have no Latitude and Longitude YET
return;
}
async function getWeather() {
let res = await axios.get(
`https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=${latitude},${longitude}&days=1&aqi=no&alerts=no`
);
console.log(res.data);
console.log(res.data.location.name);
setCity(res.data.location.name);
}
getWeather();
}, [latitude, longitude]);
Here is video to my youtube channel, where you can see a demo of this: https://youtu.be/gxcG8V3Fpbk
RESULT from API:
"location": {
"name": "Dublin",
"region": "Dublin",
"country": "Ireland",
"lat": 53.35,
"lon": -6.26,
"tz_id": "Europe/Dublin",
"localtime_epoch": 1673737376,
"localtime": "2023-01-14 23:02"
},

In case you only need the country information based on coords (lat, lng), you can use the coordinate_to_country npm package. This way you don't need to make any API. It is based on OSM country boundaries.
Otherwise, if you need more location information (city, address, neighbourhood etc.) you can explore various geocoding API's such as:
OSM - Nominatim
Mapbox Geocoding
Google Maps Geocoding
OpenCage Geocoding

Related

Highlight an existing business on Google Maps API

I have a list of store addresses, and I'm trying to create a map out of it.
Using the Places API I am able to retrieve most of the informations and manually create and place the markers on the map:
const service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery({
query: '212 Enterprise Dr, Rockaway, Frank Pizza',
fields: ['all']
}, onPlaceFound);
However I'd like to select the original marker instead of overlapping a new one.
That is because I want the user to be able to open the default info window with store phone number, directions and stuff.
I know that I can re-create it, but it feels kinda lame since all the info is already there.
This SO post ask about the same, yet no solution has been found.
Based on the documentation found here, which shows findPlaceFromQuery(), the second parameter of findPlaceFromQuery should be a function where the first argument of that function is an Array of placeResults.
Therefore, after reviewing a link here and here your onPlaceFound function should be looking something like:
function onPlaceFound(placeResultsArray){
const firstResult = placeResultsArray[0], firstIconURL = firstResult.icon;
const latLng = firstResult.geometry.location, lat = latLng.lat(), lng = latLng.lng();
// do stuff with those variables here
}
Of course, that does not select Google's result as a Marker, but now you have the actual icon, and latitude and longitude.

Add a user inputted location to OpenStreetMap using Leaflet.js

I am trying to create a map of user-inputted locations, however to do this I need to convert inputted cities into their latitude and longitude. This allows me to easily plot them using Leaflet.js using L.marker(point).addTo(map)
Given the input of say "London" is there a way using the OpenStreetMap API to fetch these values?
here are very few API tools available that will do this task (from my research) without the need for an API key.
I want to avoid using the google maps API if possible and would appreciate any help, whether it be API recommendations or OpenStreetMap ideas, as I am relatively new to javascript.
Thanks in advance!
As recommended in the comments, the solution was to use nomination, in particular, their search queries.
I ended up using jQuery's getJson function to fetch the data from the API as follows.
$(function () {
geocoding = function (city, country) {
var url = `https://nominatim.openstreetmap.org/search?city=${city}&country=${country}&format=json`
$.getJSON(url, function (data) {
//data is the JSON string
lat = data[0].lat
lon = data[0].lon
...
});
}
})

Use google's autocomplete service to search (and output) only country and/or city

I initialise google places api as follows:
<script
type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&types=cities"
></script>
and in my code, I bootstrap the service as follows:
const autocomplete = new window.google.maps.places.AutocompleteService();
autocomplete.getPlacePredictions({ input }, predictions => {
console.log(predictions);
});
autocomplete.getPlacePredictions('London');
I'd expect the query to only return a set of cities matching that query, but instead it returns a list of London based addresses.
How could I make it return only city results matching that query?
The types property cannot be added to the Maps API script itself. You need to add it to your request to AutocompleteService.getPlacePredictions as follows:
autocomplete.getPlacePredictions({ input: 'London', types : ['(cities)'] }, predictions => {
console.log(predictions);
});
Maps JS API script (without types):
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
Output:
London, UK
London, ON, Canada
London, KY, USA
Londonderry, UK
London, OH, USA
For reference check out the resources below:
AutocompletionRequest interface reference
Autocomplete for Addresses and Search Terms
Hope this helps!

How to get all place details from a Place Details Request using Google Places API Web Service?

I am trying to get data, like phone numbers, from a Place Details Request using The Google Places API Web Service. I am unable to get response data that is similar to the one shown in this guide, even though I'm getting the place id from the same address.
The place id I get is different from the one in the guide. My place id is 'ChIJ8UadyjeuEmsRDt5QbiDg720' and theirs is 'ChIJN1t_tDeuEmsRUsoyG83frY4'. If I use their place id I get all the data I need.
The only data I can get are: address_components, adr_address, formatted_address, geometry, icon, id, name, place_id, reference, scope, types, url, and vicinity. How can I get data like a phone number from a request?
var placesRequest = $http({
method: "post",
url: "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + <my place id>+"&key=<my key>"
});
placesRequest.success(function (data) {
console.log("data", data);
});
Same problem with Google Maps JavaScript API using this code.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.866, lng: 151.196},
zoom: 15
});
google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: $scope.newUserData.address.place_id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
if(place) {
console.log("place", place);
}
}
});
}
initMap();
The phone number is missing in the Google Places API because Google Maps doesn't have a phone number for that particular place. If you request the details for a place with a phone number on Google Maps, it will be returned.
Take a closer look at ChIJ8UadyjeuEmsRDt5QbiDg720. It's an office building called "Workplace 6" — notice that the details say it is of type premise. If you visit the Google Maps URL in the url field (https://maps.google.com/?q=Workplace+6&ftid=0x6b12ae37ca9d46f1:0x6defe0206e50de0e) you'll notice there's no phone number listed there either.
The other Place ID, ChIJN1t_tDeuEmsRUsoyG83frY4, is for one of the businesses located inside that building (Google). If you compare the address_components or formatted_address you'll see they don't have quite the same address (Google's address is floor 5 of that building).
In general, any field of a place might be absent. This happens if Google Maps doesn't know it, or if it simply doesn't apply (e.g. you won't find opening_hours on France). As the documentation for Place Details Results say:
Each result may contain the following fields:
[Emphasis mine.]

get the coordinates(latitude and longitude) of google map by street address - angular

so i have random street address, lets say: 5707 dogwood ave. all i want is to get the coordinates of that address so i can view my google map at the street location using angular.
i've search but wasn't able to find anything useful.
the map code(very basic map)
$scope.map = {
center: {
latitude: 33.025859,
longitude: -96.844698
},
zoom: 8
};
html code:
<google-map class="full-image" center="map.center" zoom="map.zoom"></google-map>
You can use an http.get as such to make a GET request at Google's API endpoint and retrieve a json of the address's coordinates:
$http.get('http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false').success(function(mapData) {
angular.extend($scope, mapData);
});
and you can call out the data at $scope.mapData
Refer to this StackOverflow post for more info:
Google Maps API - Get Coordinates of address
Assuming you have the address you can use the Google Geocoding web service to manually retrieve the location coordinates. (I added a city and state to better refine the data)
https://developers.google.com/maps/documentation/geocoding/
JSON:
http://maps.google.com/maps/api/geocode/json?address=5707%20dogwood%20ave.%20Rosamond,%20CA&sensor=false
XML:
http://maps.google.com/maps/api/geocode/xml?address=5707%20dogwood%20ave.%20Rosamond,%20CA&sensor=false
Alternately there is a javascript wrapper on the API
I would also review this post regarding how to deal with rate limiting if you will be exceeding 2,500 requests per day.
http://www.benbybenjacobs.com/blog/2013/09/11/google-geocoding-service-for-angularjs

Categories

Resources