Link to home
Start Free TrialLog in
Avatar of MJ
MJFlag for United States of America

asked on

Detect User's State Using JavaScript (Not using Geo-location)

Is there an easy way to find out a user's state (e.g. CA.) using JavaScript? I don't want them to have to opt-in like GEO-location. I've seen a few IP look-up options but trying to find the easiest way.

Thanks!

Avatar of leakim971
leakim971
Flag of Guadeloupe image

https://developer.mozilla.org/fr/docs/Web/API/Navigator/geolocation
=> https://w3c.github.io/geolocation-api/#navi-geo
=> https://developer.mozilla.org/fr/docs/Web/API/Geolocation/getCurrentPosition

now, you need to find a database which have delimiters of each state, did not find one yet(?) but you've this one :
https://gist.github.com/meiqimichelle/7727723

So, here a code : https://leak.im/29219001/
I got Florida and, yes, this is a closest state from my country, wonderful :)

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};


function success(pos) {
  var crd = pos.coords;
  let state = avg[0];
  let best = Math.pow(avg[0].latitude - crd.latitude, 2) + Math.pow(avg[0].longitude - crd.longitude, 2);
  for(let x=1;x<avg.length;x++) {
     let chlngr = Math.pow(avg[x].latitude - crd.latitude, 2) + Math.pow(avg[x].longitude - crd.longitude, 2);
     if(best>chlngr) {
       state = avg[x];
       best = chlngr;
    }
  }
  console.log(state.state);
  alert(state.state);
}


function error(err) {
  console.warn(`ERROR (${err.code}): ${err.message}`);
}


navigator.geolocation.getCurrentPosition(success, error, options);

Open in new window

So, here a code : https://leak.im/29219001/
I got Florida and, yes, this is a closest state from my country, wonderful :)


I got Pennsylvania yet I am in Southern Ontario, closest state is New York
I know it's not perfect as the file use average lat/lng for each state
...but, I see Pennylvania near South Ontario on my map
...and yes you know where you're living more than me @David :))

If we found a file with points delimiting states, we probably can do better than using average points... of course !

User generated image
@leakim "I don't want them to have to opt-in like GEO-location"
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MJ

ASKER

Hi,
No, I don't want to have to have the user opt-in.
Thanks!
so it's game over, you can't access user WAN IP address from a browser until you're ok to use an external web service, maybe your own and why do you need a JavaScript solution when this info is available on server side.

using CGI : https://www.oreilly.com/openbook/cgi/ch02_02.html

os.environ["REMOTE_ADDR"]

Open in new window