nLL

Mobile web, .Net, Android, gadgets and some random stuff

mobile geolocation with jquery and google maps api and asp.net c#

Below code uses google maps api with local proxy code to get country,city and local area of user. Fully functuional apart from multiple entries not being filtered in the result. I'll hopefully fix it too.

It only workd phones that support navigator.geolocation such as iPhone, webOs, Android, Nokia N900

Due to same origin policy I've had to use local proxy code to download location data from google (see below)

 

To run the code create an html file and paste below code on to it 

<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
         function find() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(success, error);
            } 
            else if ( window.google && google.gears ) {
            var geo = google.gears.factory.create( 'beta.geolocation' );
            geo.getCurrentPosition(success, error);
          }
          else {
                $('#output').html('Not supported');
            }
        }
        function success(position) {
            var lat = position.coords.latitude;
            var long = position.coords.longitude;
            var pullurl = 'getLocationResponse.ashx?latlng=' + lat + ',' + long;
            get(pullurl);
            //$('#output').html(pullurl);
        }
        function error(msg) {
            $('#output').html('failed to get coordinates');
        }
        function get(url) {
            $.ajax({
                type: "GET",
                url: url,
                dataType: "xml",
                success: parseXml,
                error: function (xhr, status, error) {
                     $('#output').html("An AJAX error occured: " + status + "\nError: " + error);
                }
            });
        }
        function parseXml(xml) {
            $(xml).find("GeocodeResponse").each(function () {
                if ($(this).find("status").text() == "OK") {
                    parseOkXml(xml)
                }
                else {
                    $('#output').html('response code was not OK');
                }
            });
        }
        function parseOkXml(xml) {
            $(xml).find('type').each(function () { // find all "type" tag in XML
                if ($(this).text() == 'administrative_area_level_1') { // in here $(this) is our "type" tag
                    add($(this).parent().find('long_name').text());
                    //return false;
                }
				 if ($(this).text() == 'administrative_area_level_2') { // in here $(this) is our "type" tag
                    add($(this).parent().find('long_name').text());
                    //return false;
                }
				 if ($(this).text() == 'administrative_area_level_3') { // in here $(this) is our "type" tag
                    add($(this).parent().find('long_name').text());
                    //return false;
                }
            });
        }
		function add(data)
		{
                $('#location').append('');
		}
    </script>

Proxy code to load maps data from google getLocationResponse.ashx

 

<%@ WebHandler Language="C#" Class="getLocationResponse" %>
using System;
using System.Web;
using System.Net;
using System.IO;

public class getLocationResponse : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/xml";
        string latlng = context.Request.QueryString["latlng"];
        string url = "http://maps.google.com/maps/api/geocode/xml?latlng=" + latlng + "&sensor=true";
        WebRequest request = WebRequest.Create(url);
        request.Timeout = 1000;
        ;


        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    context.Response.Write(reader.ReadToEnd());
                }
            }
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 you now can request location info by calling find() JavaScript function from html

Comments (2) -

  • Javo

    3/6/2012 4:54:22 PM | Reply

    Hi

    I have a problem executing $.ajax. IE shows "Access is denied", Chrome and Firefox only execute the error function without message.

  • Ed

    5/4/2012 11:05:44 AM | Reply

    I find this code very informative, even if i am not quite certain how to deploy it, but am more than sure the idea behind it can assist me power (and query) a server-side html-based database server with pre-loaded geocoordinates, for use in an app i am busy flailing around trying to create Smile

    Any ideas how to embed this in my html/webpage, and link it with my existing android app (in creation)  will be most appreciated Smile

    Cheers

Add comment