Use live search from code

This Page is locked
Modified: 2007/11/05 14:29 by ViaVE Visitor
It is possible to access the search functionality from live.com through a web service. The following code shows how you can search for addresses.

Make sure you have added:


using System.Net;

using System.Text;

using System.Text.RegularExpressions;

using System.Web;

using System.Web.Configuration;

using System.Web.Security;

using System.Xml;

using System.Xml.XPath;

using System.IO;



private void button1_Click(object sender, EventArgs e)

{

double Latitude = 0;

double Longitude = 0;

GeoCode(textBox1.Text, out Latitude, out Longitude);

lblLat.Text = Latitude.ToString();

lblLong.Text = Longitude.ToString();

}

private bool GeoCode(string Address, out double Latitude, out double Longitude)

{

bool RetVal = true;

double long2 = 0;

double long1 = 0;

double lat2 = 0;

double lat1 = 0;

Latitude = 0;

Longitude = 0;

string text1 = "a=&b=" + Address + "&c=0.0&d=0.0&e=0.0&f=0.0&g=&i=&r=0";

string text2 = DoSearchRequest(text1);

if ((text2 == null) || (text2 == string.Empty))

{

return false;

}

Regex regex1 = new Regex(@"SetViewport\((?<lat1>\S+),(?<long1>\S+),(?<lat2>\S+),(?<long2>\S+)\);VE_SearchManager");

Match match1 = regex1.Match(text2);

if (!match1.Success)

{

return false;

}

lat1 = double.Parse(match1.Groups["lat1"].Value);

long1 = double.Parse(match1.Groups["long1"].Value);

lat2 = double.Parse(match1.Groups["lat2"].Value);

long2 = double.Parse(match1.Groups["long2"].Value);

// we use the midpoint of the viewport here

Latitude = (lat1 + lat2) / 2;

Longitude = (long1 + long2) / 2;

return RetVal;

}

private string DoSearchRequest(string searchParams)

{

string text1 = string.Empty;

HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("http://dev.virtualearth.net/legacyservice/search.ashx");

request1.Method = "POST";

request1.ContentType = "application/x-www-form-urlencoded";

UTF8Encoding encoding1 = new UTF8Encoding();

byte[] buffer1 = encoding1.GetBytes(searchParams);

request1.ContentLength = buffer1.Length;

try

{

Stream stream1 = request1.GetRequestStream();

stream1.Write(buffer1, 0, buffer1.Length);

stream1.Close();

text1 = GetSearchResults(request1);

}

catch (WebException)

{

}

return text1;

}

private string GetSearchResults(HttpWebRequest searchRequest)

{

string text1 = string.Empty;

HttpWebResponse response1 = (HttpWebResponse)searchRequest.GetResponse();

Stream stream1 = response1.GetResponseStream();

Encoding encoding1 = Encoding.GetEncoding("utf-8");

StreamReader reader1 = new StreamReader(stream1, encoding1);

char[] chArray1 = new char[0x100];

for (int num1 = reader1.Read(chArray1, 0, 0x100); num1 > 0; num1 = reader1.Read(chArray1, 0, 0x100))

{

string text2 = new string(chArray1, 0, num1);

text1 = text1 + text2;

}

response1.Close();

return text1;

}


Warning!!! This more does not work