Geocode with google maps api in ASP.Net
I have spent many hours trying to find a free way to do postcode lookups and obtain the longitude and latitude. A few websites provide this service, but unfortunately i have found that after a few months the websites no longer work, or restrict the number of lookups each day.
However google have always provided a lookup facility on their google map pages, and this is now available in the API. At the moment there is only a JavaScript version available, but by populating HTML fields and sending to a ASP.NET page then these values can be obtained and used in your own code.
For this example to work you will need 2 pages. One contains the form and the other displays the results.
Enter the below code into your editor and save as "search.aspx". Remember to alter the text "REPLACE-WITH-YOUR-API-KEY" to the value of your API Key.
<html>
<head>
<script type='text/javascript' src='http://maps.google.com/maps?file=api&v=2&key=REPLACE-WITH-YOUR-API-KEY'></script>
<script type="text/javascript" src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=REPLACE-WITH-YOUR-API-KEY"></script>
<script type='text/javascript'>
var localSearch = new GlocalSearch();
function postcodelookup(postcode) {
localSearch.setSearchCompleteCallback(null, function() {
if (localSearch.results[0])
{
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
document.form1.Lng.value=point.x;
document.form1.Lat.value=point.y;
document.form1.submit();
}else{
alert("Postcode not found!");
}
});
localSearch.execute(postcode + ", UK");
}
</script>
</head>
<body>
<form name="form1" action="results.aspx" method="post">
<input name="postcode" type="text" value=""/>
<input type="button" value="Search" onclick="postcodelookup(document.form1.postcode.value);">
<input name="Lng" type="hidden"/>
<input name="Lat" type="hidden"/>
</form>
</body>
</html>
Next save the following code as "results.aspx"
<%
Dim Lat = request("lat")
Dim Lng = request("lng")
response.write(" Lat: " & lat)
response.write(" Lng: " & lng)
%>
What this code does is to call the JavaScript function "postcodelookup" which then sets up a callback function to execute when the search is complete. In this case the callback function just sets the HTML form values and submits.