Displaying City name in a div using geolocation

Ollie Mason picture Ollie Mason · Sep 12, 2013 · Viewed 10.5k times · Source

OK so I've hit a wall, simply all i want to do is propagate a div with the city name of the user at hand, I think I'm on the right lines but missing something out. Can anyone help? heres my coding:

<!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"> 
function getLocation(){
    var loc = document.getElementById('coords');
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    else
    {
        loc.value = "nolocation";
    }
}

function showPosition(position){
    var loc = document.getElementById('coords');
    loc.value = position.coords.latitude + "," + position.coords.longitude;

    var geocoder = new google.maps.Geocoder();
     var latlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {


                var area = getArea(results)
                document.getElementById('location-box').value = area;
            }
        }
    });
}

function getCountry(results)
{
    for (var i = 0; i < results[0].address_components.length; i++)
    {
        var shortname = results[0].address_components[i].short_name;
        var longname = results[0].address_components[i].long_name;
        var type = results[0].address_components[i].types;
        if (type.indexOf("country") != -1)
        {
            if (!isNullOrWhitespace(longname))
            {
                return longname;
            }
            else
            {
                return shortname;
            }
        }
    }
    return "";
}

function getArea(results)
{
    var areaName = "";
    for (var i = 0; i < results[0].address_components.length; i++)
    {
        var shortname = results[0].address_components[i].short_name;
        var longname = results[0].address_components[i].long_name;
        var type = results[0].address_components[i].types;

        if (type.indexOf("locality") != -1){
            if (!isNullOrWhitespace(shortname))
            {
                areaName += shortname;
            }
            else
            {
                areaName += longname;
            }
        }
        if (type.indexOf("administrative_area_level_2") != -1){
            if (areaName != "")
            {
                areaName += ", ";
            }
            if (!isNullOrWhitespace(shortname))
            {
                areaName += shortname;
            }
            else
            {
                areaName += longname;
            }
        }
    }
    return areaName;
}

function isNullOrWhitespace(text) {
    if (text == null) {
        return true;
    }
    return text.replace(/\s/gi, '').length < 1;
}
</script> 
</head> 
<body onload="getLocation()"> 
<div id="coords"></div>
<div id="location-box"></div>
</body> 
</html> 

In the end I want this data to be displayed in an input box if possibly to initialize a search.

Answer

scniro picture scniro · Sep 12, 2013

Here is a solution I have used to reverse geocode my location to determine my state. I hope this helps.

navigator.geolocation.getCurrentPosition(function (pos) {
    var geocoder = new google.maps.Geocoder();
    var lat = pos.coords.latitude;
    var lng = pos.coords.longitude;
    var latlng = new google.maps.LatLng(lat, lng);

    //reverse geocode the coordinates, returning location information.
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        var result = results[0];
        var state = '';

        for (var i = 0, len = result.address_components.length; i < len; i++) {
            var ac = result.address_components[i];

            if (ac.types.indexOf('administrative_area_level_1') >= 0) {
                state = ac.short_name;
            }
        }

        $('#yourInputBox').val(state);

    });
});