Thursday, May 5, 2011

Google map api for searching lat and lng by postcode and country name

This is a big achivement for Today. I was strugling with Italy google map. the issue was italy postcode has same format with US postcode. so, google api gives returns us map instead of italy map.

I solved this issue with some codes which does reference to this site

http://www.storm-consultancy.com/blog/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address/

very genius of that.
public LatLng GetLatLng(string addr)
33 {
34 var url = "http://maps.google.co.uk/maps/geo?output=csv&key=" +
35 this.API_KEY + "&q=" + HttpContext.Current.Server.UrlEncode(addr);
36
37 var request = WebRequest.Create(url);
38 var response = (HttpWebResponse)request.GetResponse();
39
40 if (response.StatusCode == HttpStatusCode.OK)
41 {
42
43 var ms = new MemoryStream();
44 var responseStream = response.GetResponseStream();
45
46 var buffer = new Byte[2048];
47 int count = responseStream.Read(buffer, 0, buffer.Length);
48
49 while (count > 0)
50 {
51 ms.Write(buffer, 0, count);
52 count = responseStream.Read(buffer, 0, buffer.Length);
53 }
54
55 responseStream.Close();
56 ms.Close();
57
58 var responseBytes = ms.ToArray();
59 var encoding = new System.Text.ASCIIEncoding();
60
61 var coords = encoding.GetString(responseBytes);
62 var parts = coords.Split(",");
63
64 return new LatLng(
65 Convert.ToDouble(parts[2]),
66 Convert.ToDouble(parts[3]));
67 }
68
69 return null;
70 }
71 }

Have fun with this !

No comments: