Thursday, October 6, 2016

Implementing Google Maps

My project for Pinedale Properties implements Google Maps by showing property locations Below is the source code for how I implemented this solution. This code was done using ASP .NET 2.0.

First we have to insert the Script Source for the Google Map API... Don't forget to use your own key.

<script src="http://maps.google.com/maps?file=api&v=2&key=KEYHERE" type="text/javascript">script

Next up we need to modify the body tag to execute the script on load, and to call the GUnload() function on unload.

<body onload="Page_Load()" onunload="GUnload()">


On the control that displays the google map, I've added the following HTML Field...

<div id="map" style="WIDTH: 350px; HEIGHT: 600px">div>

Once all of that is finished, it's time to go play in the source code...

In the source, code, I first insert the Javascript code that is always present

'MAP HEADER CODE
sbGoogleCode.Append(""text/javascript" & Chr(34) & ">" & vbCrLf)
sbGoogleCode.Append("//
' place icon on map
sbGoogleCode.Append("var icon" & num & "= new GIcon();" & vbCrLf)
sbGoogleCode.Append("icon" & num & ".image = " & Chr(34) & "MapIcons/" & num & ".gif" & Chr(34) & ";" & vbCrLf)
sbGoogleCode.Append("icon" & num & ".shadow = " & Chr(34) & "images/shadow.gif" & Chr(34) & ";" & vbCrLf)
sbGoogleCode.Append("icon" & num & ".iconSize = new GSize(47, 53);" & vbCrLf)
sbGoogleCode.Append("icon" & num & ".shadowSize = new GSize(73, 53);" & vbCrLf)
sbGoogleCode.Append("icon" & num & ".iconAnchor = new GPoint(22, 53);" & vbCrLf)
sbGoogleCode.Append("icon" & num & ".infoWindowAnchor = new GPoint(4, 1);" & vbCrLf)
sbGoogleCode.Append("var point" & num & " = new GLatLng(" & lat & ", " & longitude & ");" & vbCrLf)
sbGoogleCode.Append("map.addOverlay(new GMarker(point" & num & ", icon" & num & "));" & vbCrLf)
End If
End Sub

This function takes in as parameters, the latitude, longitude, and a number. Latitude and longitude should be standard enough. The number tells the javascript which image to display on the map. (ie #1 for the first listing, #2 for the second, etc.)


Finally, after that code is generated, I add in the finishing touches to the Javascript.

sbGoogleCode.Append("}" & vbCrLf)
sbGoogleCode.Append("}" & vbCrLf)
sbGoogleCode.Append("//]]>" & vbCrLf)
sbGoogleCode.Append(")
sbGoogleCode.Append("script>")
Finally after that is completed, add the Javascript code to the page using the ClientScript.RegisterStartupScript function as shown here.

If (Not Page.ClientScript.IsStartupScriptRegistered("clientScript")) Then
Page.ClientScript.RegisterStartupScript(Me.GetType(), "clientScript", sbGoogleCode.ToString, False)
End If

As I move down the road, I see myself updating this feature with some additional features. Such as being able to click on a property in the list and having it highlight the map marker. Below is the finish product.



No comments: