How to get the zipcode of a user using AngularJS - javascript

I need to populate some data based on the zipcode of the user visiting the site.
Could somebody tell me how to retrieve the zipcode of the location of that user?
I am using AngularJS on my app.

OK. It is a bit involved, but here is how I would do it, if I were you.
First, you would use the geolocation API as follows:
window.navigator.geolocation.getCurrentPosition(function(pos){
console.log(pos);
});
Inside your callback, you will get a position object. It looks like this:
{
"timestamp":1408324851386,
"coords"{
"speed":null,
"heading":null,
"altitudeAccuracy":null,
"accuracy":30,
"altitude":null,
"longitude":-111.8942634,
"latitude":40.7288257
}
}
Then, you can take the latitude and longitude and call your server to translate it into a ZIP code. Getting the lat/long is the hard part. Doing the math to turn that into a zip is easy.
An alternative to calling your own server to translate the lat/long into a zip, you could call Google Maps' reverse lookup API. You give it a lat long, and it gives you an address, complete with a ZIP. See HERE for how to do that.
DISCLAIMER: This won't work in IE8, as the geolocation API wasn't introduced until IE9. It will work in all other browsers (besides Opera Mini, #NBD).
HERE IS A FULL WORKING EXAMPLE
I just tried this out, and it found my house, no problem.
window.navigator.geolocation.getCurrentPosition(function(pos){
console.log(pos);
$http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+pos.coords.latitude+','+pos.coords.longitude+'&sensor=true').then(function(res){
console.log(res.data);
});
})

There doesn't seem to be any built-in method for determining this, you'll have to use a map service or zipcode database.

Related

How can I use geolocation in my node.js to get user device lat/long

Good day all, pardon my question logic as I am new here. I am building my first fullstack App using React and Node.I am thinking of three approaches but not sure what will work best.
APPROACH ONE
I want to be able to get user lat/long when they fill a form in the frontend and request access to their geolocation through the geolocation API. For example, when a user submit their region and community name, the backend will call the getCurrentPosition geolocation API. Then the returned lat/long will form part of the data to be sent to the database as shown in the extracted code below. But when I tried this approach, I ran into two challenges. First, an error message that navigator is not defined. Second, I don't know how to retrieved the lat/long returned and declare it as a const to use it in creating the location. See the code below:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert("Your browser is out of fashion. There is no geo location!")
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude
console.log(`Your latitude is ${latitude} and your longitude is ${longitude}`)
return (latitude, longitude);
}
function error() {
alert("Can't detect your location. Try again later.")
}
How do I declare the lat/long as a const outside the function. Some like:
const communityName = req.body.communityName;
const latitude = (success).latitude;
const longitude = (success).longitude;
APPROACH 2
I downloaded the geolocation npm package and use it as in code below but get the error that navigator is not defined. If I am to use this approach, how can I define navigator and how can I get to declare the lat/long as a const outside of the function?
const geolocation = require('geolocation');
geolocation.getCurrentPosition(function (err, position) {
if (err) throw err
console.log(position)
})
APPROACH 3
I read about this approach but can't get a working example. It is suggested that I should use the geolocation API to get the user device lat/long and send the coords as part of req.body data to the backend API. If this is a good approach, is there a tutorial I can follow?
Please I am new to Javascript and coding but I have made serious progress but this as got me stocked on my project. No answer is too wrong lease. There is sense in nonsense.
navigator.geolocation
This is an API provided by browsers. It isn't available to Node.js.
I downloaded the geolocation npm package
This wraps navigator.geolocation. It is designed for when you are writing client-code code using Node modules and a compilation step such as provided by Webpack. It doesn't work with Node.js.
It is suggested that I should use the geolocation API to get the user device lat/long and send the coords as part of req.body data to the backend API.
MDN and Google both provide introductions to the fetch API for making HTTP requests from client-side JavaScript.
There is also some React-specific information in the React FAQ.
You can then read the data in a different endpoint with req.body providing you have configured a suitable body-parsing middleware.

Not able to fetch Latitude and longitude from eventbrite api

This is a query string to fetch all popular events within a radius of a specified location.
https://www.eventbriteapi.com/v3/events/search/?popular=off&location.address="+area+"&location.within="+radius+"&token=E5DRAICK4272QQQIBDR5
But when I query Eventbrite api I only get venue_id , How to fetch lat and long for an event from eventbrite api ?
Please try venue param in your fetching URL to eventBrite API, like this:
$search_url?token=$token&q=&date_created.keyword=today&page=$repeat&sort_by=$date&expand=venue
It solved my issue and brought lat long along with proper location of event.
&expand=venue is still working perfectly!!! The official documentation says the venue is deprecated, but anyway you can use it.

Get user's location (latitude, longitude) when visited

Whenever a user enters my site, i want to get his longitude, latitude to further use in my google maps. I have tried using HTML5 geolocation script and geocoder gem.
Using Geocoder gem, my hash is empty when trying below code, why is this happening ? Is this because i am running it in localhost ? Please suggest how to get it done if any other way.
I just need latitude and longitude of my user, thats it.
location = request.location
longitude = location.data['longitude']
If you had carefully read documentation of geocoder gem you would notice that:
Note that these methods will usually return nil in your test and
development environments because things like "localhost" and "0.0.0.0"
are not an Internet IP addresses.

Getting geolocation from IP address

I need to track user details, for that client's location and IP address is needed.
I got IP address from
$this->input->ip_address();
in codiigniter. Now the problem is how can i make their location in google map by using their respective IP address
just use ipinfo.io at
http://ipinfo.io/
it uses a location api that we can post ip address and it will returns the location details as json:
we can able to display the loacation on map with the langitude and longitude details from json response to google Maps API.
Here is the code i used:
this script creates a Google Map instance with lattitude & longitude from json response:
jQuery(document).ready(function(){
jQuery.get("http://ipinfo.io/202.88.237.138", function (response)
{
var lats = response.loc.split(',')[0];
var lngs = response.loc.split(',')[1];
map = new GMaps({
el: '#map',
lat: lats, //latitude
lng: lngs //longitude
});
}, "jsonp");
});
and the map will displayed on:
<div style="border:1px solid red; height:745px;" id="map"></div>
Google Maps API gmaps.js is needed to run this..
As a viable (although often less accurate) alternative, the HTML5 spec includes Geolocation. As HTML 5 becomes more and more prevalent I think we can expect to see this become standard in the future. It also does not require the use of external web services or libraries. Everything you need to geolocate is built right into the clients browser.
I believe the primary method used is IP address as specified.
The Google Maps API will do the work of finding location using geoip for you. If the user is on a mobile device or has a more accurate way of locating themselves (like a GPS), it'll use that instead.
Here's a good starting point:
https://google-developers.appspot.com/maps/documentation/javascript/examples/map-geolocation
If you absolutely need to fetch location from IP only, there are third-party tools that you can scrape to get this information. You should make sure you have permission beforehand if you're using this in a larger project.
freegeoip.net provides a public HTTP API to search the geolocation of IP addresses. It uses a database of IP addresses that are associated to cities along with other relevant information like time zone, latitude and longitude.
You're allowed up to 15,000 queries per hour.
If you need more than that, you can run the freegeoip as a web server on your own infrastructure. See: freegeoip on github

Google geocoder returns wrong coordinates for address

I plot locations of real estate on a map. The address listed below is mapped incorrectly because it is a new build and I assume the street and everything is a new build, which is the reason Google can't find it in it's database.
What I want to happen is Google return "GeocoderStatus.ZERO_RESULTS" and not just pick a location with a related name and give me those coords.
The address I'm plotting is:
14018 Lonecreek Ave
Orlando, Florida 32828
If you submit the request via http, you get the same results i get through the API, see this link: http://maps.googleapis.com/maps/api/geocode/json?address=140
You'll see it comes back with "Lone Hill Drive" which is incorrect location. How can I tell Google return ZERO_RESULTS status in this instance?
Google's geocoding process isn't perfect (none are.)
What you can check for is the result's geometry.location_type property and test if it's value is "APPROXIMATE" to see if you can trust the returned lat/lng. Read more in the Documentation.
If it's way off you can report it directly to google.
You can use the API's Component Filtering to filter the results by a specific postcode. In such cases a non-exact match will have location_type of "APPROXIMATE" rather than the "GEOMETRIC_CENTER" you were seeing before.
http://maps.googleapis.com/maps/api/geocode/json?address=[address]&components=postal_code:[postcode]&sensor=false
Here's your geocoding request WITH component filtering
and WITHOUT component filtering

Categories