How to identify which city the user is? [duplicate]

13

In some sites of purchases / services is made an identification or suggestion of the city that the user is to be able to show only the specific products / services of the city of the user.

Detail, this will be used only for non-registered users, why I will be obliged to register the city and thus I can make the filter correctly, but without this record how can I do it?

    
asked by anonymous 29.12.2015 / 18:55

3 answers

12

You have several examples and codes ready on the internet, but basically what you should do is:

1) Get the coordinates with HTML5 Geolocation: w3schools - HTML5 Geolocation

//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get latitude and longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
}

2) Get the city from the coordinates with the google API: Google Developers - Geocoding

"http://maps.googleapis.com/maps/api/geocode/jsonlatlng='+lat+','+long+'&sensor=true"

Code sample:

stackoverflow - Get city name using geolocation

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Reverse Geocoding</title> 

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script><scripttype="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

function initialize() {
    geocoder = new google.maps.Geocoder();
}

function codeLatLng(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
      if (results[1]) {
        //formatted address
        alert(results[0].formatted_address)
        //find country name
        for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0; b<results[0].address_components[i].types.length;b++) {

              //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data
        alert(city.short_name + " " + city.long_name)


        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html> 
    
29.12.2015 / 19:09
10

Use GeoIP, it does not give the exact location of the city, but the approximate region of your access point through the user's IP.

Example

<?php
$record = geoip_record_by_name('192.168.0.1');
if ($record) {
    print_r($record);
}
?>

The variable $record returns values such as, continent, country, cities, longitude, region, area code, etc.

To find the returned parameters, take a look at the manual .

Obs

Requires installation.

Installation for Linux / Windows

Installation on Linux (OpenSuse)

    
29.12.2015 / 19:05
5

Using HTML5 Geolocation and OpenStreetMaps Geographic Data:

navigator.geolocation.getCurrentPosition(function(posicao) {
    var url = "http://nominatim.openstreetmap.org/reverse?lat="+posicao.coords.latitude+"&lon="+posicao.coords.longitude+"&format=json&json_callback=preencherDados";

    var script = document.createElement('script');
    script.src = url;
    document.body.appendChild(script);
});



function preencherDados(dados) {
  alert(dados.address.city);  
}
    
29.12.2015 / 19:06