How to identify which city the user is in?

Asked

Viewed 14,607 times

14

On some shopping/service sites an identification or suggestion is made of the city the user is in order to show only the products/services specific to the user’s city.

Detail, this will be used only for users not registered, why I will be forcing the registration of the city and so I can make the filter correctly, but without this record as I can do ?

  • Usually by Geoip

  • It is worth noting that it is good to use only as a suggestion, as there is currently no precise method of determining this. (unless it is a device with GPS, and it is released. and yet, the information may not be correct).

  • Related: http://answall.com/questions/106002/best-m%C3%A9all-discover-the-status

3 answers

13


There are 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: Developers google - Geocoding

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

Code example:

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> 
<script type="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> 
  • 3

    Antonio, I know that these links can have a very useful content,but prefer to carry the essential in your answer, a code example an explanation, why the links can break and your answer will no longer be valid.

  • To post links, you can use the comment field. To prepare a response, it is important to illustrate, because if the links stop working, your answer is not invalid.

  • +1 took the city correctly, but the accuracy of the sector was very weak, took a sector that is 25km from here kkkk, imagine if it is a small town, will locate ?

  • I am in a very small town (7k inhabitants) and he detected a neighboring town (it is 10km from here). The accuracy of Geolocation varies by browser and device. In general, it is more accurate than localization only by IP, as it has access to all the localization features that the browser provides.

  • Well, I know that it is much better than GEO IP, but it is always good to let the user change if it is necessary... For example if you are pre-filling a field with Geolocation data it would be good to leave the editable field...

12

Use Geoip, it does not give the exact location of the city, but 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 know the returned parameters, take a look at manual.

Obs

Requires installation.

Installation for Linux / Windows

Installation on Linux (Opensuse)

  • Do you have any details about enabling the same ? I’m using php 5.6.9 and in my php.ini did not find any geoip extension to enable...

  • 1

    I edited the answer with the installation tutorial: http://php.net/manual/en/geoip.setup.php

8

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);  
}
  • 1

    I think if I put an example of using Geolocation it makes the answer more complete. The reverse location part is already good.

  • Very cool, this Openstreetmaps, it has some differential because its accuracy is identical to that of google maps is clear in the tests I performed here

  • For those using Jquery, like me, remove the last querystring parameter and run: $.getJSON(url, filledDados);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.