Rohan
Rohan

Reputation: 2935

How to retrieve the latitude and longitude of the inputed address using google geo coder?

I want to display the latitude and longitude values in the 2 text boxes when the user enter his address as street, city, state and zipcode. I am using google geocoder.

i have used the following code on button click :

   protected void BtnShow_Click(object sender, EventArgs e)
    {
        GetLatLongFromAddress(TxtStreet.Text, TxtCity.Text, TxtZipcode.Text,   TxtState.Text);
    }

    private void GetLatLongFromAddress(string street, string city, string zipcode, string state)
    {

        string geocoderUri = string.Format(@"http://maps.googleapis.com/maps/api/geocode/xml?address={0},{1},{2},{3}&sensor=false", street, city, zipcode, state);


        XmlDocument geocoderXmlDoc = new XmlDocument();
        geocoderXmlDoc.Load(geocoderUri);

        XmlNamespaceManager nsMgr = new XmlNamespaceManager(geocoderXmlDoc.NameTable);
        nsMgr.AddNamespace("geo", @"http://www.w3.org/2003/01/geo/wgs84_pos#"); 


        string sLong = geocoderXmlDoc.DocumentElement.SelectSingleNode(@"geo:long", nsMgr).InnerText;
        string sLat = geocoderXmlDoc.DocumentElement.SelectSingleNode(@"//geo:lat", nsMgr).InnerText;

        TxtLatitude.Text = sLat;
        TxtLongitude.Text = sLong;
    }

But it gets the value of sLong variable as null and shows an error

   "Object reference not set to an instance of an object."

How can i do this ?

waiting for answer...

thnks..

Upvotes: 1

Views: 4865

Answers (2)

Frank
Frank

Reputation: 1

I used your code and the error was on the xPath, I changed it to this

string sLong = geocoderXmlDoc.DocumentElement.SelectSingleNode(@"//geometry/location/lat", nsMgr).InnerText;

string sLat = geocoderXmlDoc.DocumentElement.SelectSingleNode(@"//geometry/location/lng", nsMgr).InnerText;

Everything is working fine now.

Upvotes: 0

Antonio Bakula
Antonio Bakula

Reputation: 20693

For that purpose I am using excelent GoogleMap control, see details here :

http://googlemap.codeplex.com/wikipage?title=Google%20Geocoder&referringTitle=Documentation

On this link you have example for server side usage, you can use it from client also, this example is using GeoCoder API to position place on map based on place name.

  function DoMapSearch(placeName) {
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(placeName, function (point) {
      if (point != null) {
        GoogleMapCnt.loadAddress(addr);
      }
    });

    return false;
  }

Upvotes: 2

Related Questions