Geo-tag Your Photos Using ASP.NET and Google Maps: Part I
Getting Started with the Google Maps API
October 30, 2009
CoverStory
LANGUAGES: JavaScript | VB.NET
ASP.NET VERSIONS: 2.0
Geo-tag Your Photos Using ASP.NET and Google Maps: Part I
Getting Started with the Google Maps API
By Wei-Meng Lee
The Google Maps API is a free mapping service that allowsyou to embed maps into your Web pages using JavaScript. Besides displayingmaps, Google Maps enables you to insert markers at landmarks of interest. Thisfeature is very exciting because you can use it to associate photos withdifferent geographical locations (a process known as geo-tagging). For example,you can display your vacation photos in Google Maps so that, besides viewingthe photos, you know the exact location where you took the photos.
This two-part series demonstrates how to build an ASP.NETWeb application that allows users to upload photos and geo-tag them usingGoogle Maps. Part I shows you how to get started with the Google Maps API.
Using Google Maps
To use Google Maps, you must sign up for a Maps API key athttp://www.google.com/apis/maps/signup.html.However, the key for which you apply is only valid for a particular directoryon your Web server. For example, if you want to display a map onwww.mysite.com/myApp/mypage.html, you must apply for a Maps API key forwww.mysite.com/myApp/; this key will only work for the pages in this directory.
Note: Because theGoogle Maps API key is tied to the URL of your Web application, you cannot useGoogle Maps within a Windows application.
Creating the Application
Using Visual Studio 2005, create a new ASP.NETAJAX-enabled Web Site project and name it GoogleMaps. Once the project iscreated, press F5 to run it. The main purpose is to get the URL for the Webapplication so you can apply for a valid Maps API key for this application. I musing the built-in Web server that shipped with Visual Studio 2005, so my URLlooks something like this: localhost:2139/GoogleMaps/. You ll most likely havea different port number (2139, in my case), but use your own URL to apply for aMaps API key.
Tip: For development purposes, it is good to set the Usedynamic ports property of the project to False so Visual Studio 2005 willalways use the same port number for your project (set the port number in thePort number property; see Figure 1).
Figure 1: Use a static port numberfor your ASP.NET Web application.
Once you have a valid Maps API key, you can use GoogleMaps easily. Insert in the Source View of the Default.aspx page the element containing the JavaScript that will load the Google Maps, as shown inbold in Figure 2. </p><p> </p><p><head id="Head1" runat="server"> </p><p> <title>UntitledPage</title> </p><p><b> <script src="http://maps.google.com/maps?file=api& </b></p><p><b> v=2&key=ABQIAAAA26ROxQdKhHJQA3ZbT3HkSBTWrCUD1_</b></p><p><b> 1cGNyM6E4_IspVr1prIxQPz04xVq0xNfzxTGPpQ_lcCEcotQ" </b></p><p><b> type="text/javascript"> </b></p><p><b>
function load() {
if (GBrowserIsCompatible()) {
var map = newGMap2(document.getElementById("map"));
//---set the center point for the map---
map.setCenter(new
GLatLng(37.65528588731535,-122.40726470947265), 13);
}
}
Figure 2: The element containing the JavaScript that will load the Google Maps.</p><p> </p><p> Note that you must replace the following: </p><p> </p><p>key=ABQIAAAA26ROxQdKhHJQA3ZbT3HkSBTWrCUD1_1cGNyM6E4_</p><p>IspVr1prIxQPz04xVq0xNfzxTGPpQ_lcCEcotQ</p><p> </p><p> with your own key: </p><p> </p><p>key=your_own_valid_Maps_API_key</p><p> </p><p> Also, insert the following (shown in bold) in the <body>element so that, when the page is loaded, the JavaScript load function will beinvoked to load the Google Maps: </p><p> </p><p><body <b>onload="load()"</b>> </p><p> <formid="form1" runat="server"> </p><p> <b> <div id="map" style="width: 500px; height:300px"></div> </b></p><p> </form> </p><p></body> </p><p> </p><p> That s it! Press F5 to test the application. You shouldnow be able to see the Google Maps (see Figure 3).</p><p> </p><p><img width="333" height="268" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image004.gif"><br><b>Figure 3:</b> Viewing Google Maps on theDefault.aspx page. </p><p> </p><h3>Map Navigation</h3><p> Now that you have Google Maps working, let s modify theapplication so we can get more out of Google Maps. (You ll find the onlinedocumentation of the API very useful as you dive deeper into the Google MapsAPI: <a href="https://www.google.com/apis/maps/documentation/reference.html#GMap2">http://www.google.com/apis/maps/documentation/reference.html#GMap2</a>.)</p><p> </p><p> First, let s add two TextBox controls and one buttoncontrol to the Default.aspx page (see Figure 4). Figure 5 shows how theDefault.aspx page should now look. </p><p> </p><p><form id="form1" runat="server"> </p><p> <divid="map" style="width: 500px; height: 300px"> </p><p> </div> </p><p><b> Latitude</b></p><p><b> <asp:TextBox ID="txtLatitude"runat="server"></asp:TextBox> </b></p><p><b> <br /> </b></p><p><b> Longitude</b></p><p><b> <asp:TextBox ID="txtLongitude"runat="server"></asp:TextBox> </b></p><p><b> <br /> </b></p><p><b> <input id="btnGotoLocation"type="button" </b></p><p><b> value="Go to Location"onclick="goto_map_position()" /> </b></p><p><b> <br /> </b></p><p></form> </p><p><b>Figure 4:</b> Add twoTextBox controls and one button control to the Default.aspx page.</p><p> </p><p><img width="333" height="266" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image006.gif"><br><b>Figure 5:</b> The Design View ofDefault.aspx. </p><p> </p><p> For the button control, I used the HTML Input elementinstead of the ASP.NET Button control. This is because I don t need a postbackto occur when the button is clicked. Instead, it will directly invoke theJavaScript goto_map_position function (as set in the onclick attribute) whenclicked. </p><p> </p><p> Here are the new features to be added to our application: </p><ul><li>As the map is dragged, the latitude andlongitude will be updated on the two TextBox controls. </li><li>You can also go to a specific location byentering the latitude and longitude of the new location and clicking the Go toLocation button. </li></ul><p> </p><p> Back in the Source View of Default.aspx, move thedeclaration of the map variable to the top, making it a global variable: </p><p> </p><p><script type="text/javascript"> </p><p><b>var map = null; </b></p><p> </p><p> Next, rewrite the load function as shown in Figure 6. </p><p> </p><p>function load() {</p><p> if(GBrowserIsCompatible()) {</p><p> map = new GMap2(document.getElementById("map")); </p><p> //---displaynavigational controls---</p><p> map.addControl(newGSmallMapControl());</p><p> //---displayMap/Satellite/Hybrid---</p><p> map.addControl(newGMapTypeControl());</p><p> //---fired when the mapis dragged---</p><p> GEvent.addListener(map,"moveend",</p> <p> function()</p><p> { </p><p> var center =map.getCenter();</p><p> //---update thelat and lng in the TextBox controls---</p><p> document.forms[0].txtLatitude.value = center.lat();</p><p> document.forms[0].txtLongitude.value = center.lng();</p><p> } </p><p> ); </p><p> //---display aparticular location on the map---</p><p> map.setCenter(new</p><p> GLatLng(37.65528588731535, -122.40726470947265), 13); </p><p> } </p><p>}</p><p><b>Figure 6:</b> Rewritethe load function.</p><p> </p><p> The load function essentially adds to the map thenavigation controls, as well as the types of map controls. You then add anevent handler (moveend) so that when the user employs the mouse to drag themap, you ll display the latitude and longitude information in the two TextBox controlswhen they release the mouse button. Note that the latitude and longitudeinformation displayed always refers to the center of the map.</p><p> </p><p> Figure 7 shows that the changes made in the load functionwill cause the map to display the navigational controls, as well as thedifferent types of maps from which you can choose (Map, Satellite, or Hybrid). </p><p> </p><p><img width="333" height="233" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image008.gif"><br><b>Figure 7:</b> Displaying the additionalcontrols on the map. </p><p> </p><p> Next, define the goto_map_position function, which isinvoked when the user clicks the Go to Location button: </p><p> </p><p>//---navigate to a particular location---</p><p>function goto_map_position()</p><p>{</p><p> //---extract the lat andlng from the TextBox controls---</p><p> var lat =document.forms[0].txtLatitude.value; </p><p> var lng =document.forms[0].txtLongitude.value; </p><p> map.panTo(newGLatLng(lat,lng)); </p><p>}</p><p> </p><p> The goto_map_position function moves the map to thelocation specified using the panTo method.</p><p> </p><p> To test the application, press F5 in Visual Studio 2005.Drag the map and observe the change in the latitude and longitude information.To centralize a location on the map, double-click on the location and theselected location will appear in the center of the map (see Figure 8).</p><p> </p><p><img width="333" height="311" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image010.gif"><br><b>Figure 8:</b> Navigating to a particularlocation.</p><p> </p><h3>Adding a Marker to the Map</h3><p> Now that you ve successfully loaded Google Maps on yourpage, let s add some new interesting features to it. You can add a marker to alocation so you can use it as a reference point. To do so, let s first definethe AddMarker JavaScript function: </p><p> </p><p>function AddMarker()</p><p>{</p><p> //---set the location toadd the photo---</p><p> var centerPoint = newGPoint(</p><p> document.forms[0].txtLongitude.value,</p> <p> document.forms[0].txtLatitude.value);</p> <p> //---create a new markerobject---</p><p> var marker = newGMarker(centerPoint); </p><p> //---add the marker---</p><p> map.addOverlay(marker);</p> <p>}</p><p> </p><p> The AddMark function creates a marker, then adds it to themap using the latitude and longitude specified in the two TextBox controls. Next,add the AJAX ScriptManager control to the top of the page and set itsEnablePartialRendering attribute to true: </p><p> </p><p><body onload="load()"> </p><p> <form id="form1"runat="server"> </p><p> <b> <asp:ScriptManager ID="ScriptManager1"runat="server" </b></p><p><b> EnablePartialRendering="true"> </b></p><p><b> </asp:ScriptManager> </b></p><p> <div id="map"style="width: 500px; height: 300px"> </p><p> </div> </p><p> </p><p> Insert an UpdatePanel control on the page; within its <ContentTemplate>element, add an Add Marker button: </p><p> </p><p> <inputid="btnGotoLocation" type="button"</p> <p> value="Go toLocation" onclick="goto_map_position()" /> </p><p> <br /> </p><p><b> <br /> </b></p><p><b> <asp:UpdatePanelID="UpdatePanel1" runat="server"> </b></p><p><b> <ContentTemplate> </b></p><p><b> <asp:ButtonID="btnAddMarker" runat="server" </b></p><p><b> Text="Add Marker"Width="104px" </b></p><p><b> OnClientClick="AddMarker()" /> </b></p><p><b> </ContentTemplate> </b></p><p><b> </asp:UpdatePanel> </b></p><p></form> </p><p> </p><p> Notice that I ve used a Button control instead of the HTMLInput element. Either method is acceptable. For the Button control, set theOnClientClick attribute to AddMarker so it will invoke the AddMarker functionwhen clicked. Figure 9 shows how the page should look.</p><p> </p><p><img width="247" height="190" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image012.gif"><br><b>Figure 9:</b> Default.aspx with the newcontrols added. </p><p> </p><p> Press F5 in Visual Studio 2005 to test the application.Select a location and click the Add Markerbutton; you ll notice that Google Maps displays an icon at the locationselected (see Figure 10).</p><p> </p><p><img width="333" height="321" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image014.gif"><br><b>Figure 10:</b> Adding a marker to themap. </p><p> </p><p> Besides adding an icon to represent the marker, you canalso display a balloon when the marker is clicked. To do so, add an eventhandler to the marker using the GEvent.addListener method (see Figure 11).</p><p> </p><p>function AddMarker()</p><p>{</p><p> //---set the location toadd the photo---</p><p> var centerPoint = newGPoint(</p><p> document.forms[0].txtLongitude.value,</p> <p> document.forms[0].txtLatitude.value);</p> <p> //---create a new markerobject---</p><p> var marker = newGMarker(centerPoint);</p> <p><b> //---add the click event for the marker---</b></p><p><b> GEvent.addListener(marker,"click", </b></p><p><b> function() {</b></p><p><b> //---open the marker info tab---</b></p><p><b> marker.openInfoWindowHtml("<b>Marker 1</b>"); </b></p><p><b> }); </b></p><p> //---add the marker---</p><p> map.addOverlay(marker); </p><p>}</p><p><b>Figure 11:</b> Add anevent handler using the GEvent.addListener method to display a balloon when themarker is clicked.</p><p> </p><p> When the marker is clicked, it will display the contentspecified as the argument for the openInfoWindowHtml method (from the markerobject). The openInfoWindowHtml method takes in a single parameter, which canbe plain text or an HTML string. Figure 12 shows the marker displaying aballoon showing the text Marker 1 . </p><p> </p><p><img width="333" height="321" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image016.gif"><br><b>Figure 12:</b> Displaying a balloon on amarker. </p><p> </p><p> When you click elsewhere on the map, the balloon willdisappear. To view the balloon again, click on the marker. You can alsoorganize into tabs the information displayed in the balloon (see Figure 13); Figure14 shows the balloon organized into two tabs. </p><p> </p><p>function AddMarker()</p><p>{</p><p><b> var infoTabs = [ </b></p><p><b> new GInfoWindowTab("Tab 1","Content for tab 1"), </b></p><p><b> new GInfoWindowTab("Tab 2","Content for tab 2") </b></p><p><b> ]; </b></p><p> //---set the location toadd the photo---</p><p> var centerPoint = newGPoint(</p><p> document.forms[0].txtLongitude.value,</p> <p> document.forms[0].txtLatitude.value);</p> <p> //---create a new markerobject---</p><p> var marker = newGMarker(centerPoint);</p> <p><b> //---add the click event for the marker---</b></p><p><b> GEvent.addListener(marker,"click", </b></p><p><b> function() {</b></p><p><b> //---open the marker info tab---</b></p><p><b> marker.openInfoWindowTabsHtml(infoTabs); </b></p><p><b> }); </b></p><p> //---add the marker---</p><p> map.addOverlay(marker);</p> <p> //---open the markerinfo tab---</p><p> marker.openInfoWindowTabsHtml(infoTabs);</p> <p>}</p><p><b>Figure 13:</b> Organizeinto tabs the information displayed in the balloon.</p><p> </p><p><img width="333" height="321" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image018.gif"><br><b>Figure 14:</b> Displaying tabs in amarker. </p><p> </p><p> You can drag the marker to another position after addingit to the map. To do so, you must specify that the marker is draggable at thetime you create the marker object. You also need to add two event handlers,dragstart and dragend. The dragstart event is fired when the marker is dragged(with the mouse button down). The dragend event is fired when the user releasesthe mouse button. As shown in Figure 15, when the user starts to drag themarker, I ll hide the balloon and display another balloon when the userreleases the mouse button. Figure 16 shows the marker before and afterdragging.</p><p> </p><p>function AddMarker()</p><p>{</p><p> var infoTabs = [ </p><p> newGInfoWindowTab("Tab 1", "Content for tab 1"),</p> <p> newGInfoWindowTab("Tab 2", "Content for tab 2")</p> <p> ]; </p><p> //---set the location toadd the photo---</p><p> var centerPoint = newGPoint(</p><p> document.forms[0].txtLongitude.value,</p> <p> document.forms[0].txtLatitude.value);</p> <p><b> //---create a new draggable marker object---</b></p><p><b> var marker = new GMarker(centerPoint,{draggable: true});</b></p><p> //---add the click eventfor the marker---</p><p> GEvent.addListener(marker, "click",</p> <p> function() {</p><p> //---open the markerinfo tab---</p><p> marker.openInfoWindowTabsHtml(infoTabs); </p><p> });</p><p><b> //---start dragging---</b></p><p><b> GEvent.addListener(marker,"dragstart", function() {</b></p><p><b> map.closeInfoWindow();</b></p><p><b> }); </b></p><p><b> //---end dragging---</b></p><p><b> GEvent.addListener(marker, "dragend",function() {</b></p><p><b> marker.openInfoWindowHtml("Markermoved!"); </b></p><p><b> }); </b></p><p> //---add the marker---</p><p> map.addOverlay(marker);</p> <p> //---open the markerinfo tab---</p><p> marker.openInfoWindowTabsHtml(infoTabs);</p> <p>}</p><p><b>Figure 15:</b> The dragstartand dragend event handlers.</p><p> </p><p><img width="333" height="161" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image020.gif"><br><b>Figure 16:</b> Moving a marker. </p><p> </p><p> Because the content for the balloon can take in an HTMLstring, you can easily insert images into the balloon by using the <img>HTML element. The example in Figure 17 inserts into the balloon a picture fromanother site; Figure 18 shows how the balloon looks. </p><p> </p><p>function AddMarker()</p><p>{</p><p><b> //---HTML for displaying the photo---</b></p><p><b> var content = '<img width="300"Height="210" </b></p><p><b> src="http://www.visitingdc.com/images/</b></p><p><b> golden-gate-bridge-picture.jpg"/>'; </b></p><p> var infoTabs = [ </p><p><b> new GInfoWindowTab("Tab 1",content), </b></p><p> newGInfoWindowTab("Tab 2", "Content for tab 2")</p> <p> ]; </p><p> //---set the location toadd the photo---</p><p> var centerPoint = newGPoint(</p><p> document.forms[0].txtLongitude.value,</p> <p> document.forms[0].txtLatitude.value);</p> <p> var marker = newGMarker(centerPoint, {draggable: true});</p><p> //---add the click eventfor the marker---</p><p> GEvent.addListener(marker, "click",</p> <p> function() {</p><p> //---open the markerinfo tab---</p><p> marker.openInfoWindowTabsHtml(infoTabs); </p><p> });</p><p> //---start dragging---</p><p> GEvent.addListener(marker, "dragstart", function() {</p><p> map.closeInfoWindow();</p><p> }); </p><p> //---end dragging---</p><p> GEvent.addListener(marker, "dragend", function() {</p><p> marker.openInfoWindowHtml("Markermoved!"); </p><p> }); </p><p> //---add the marker---</p><p> map.addOverlay(marker);</p> <p> //---open the markerinfo tab---</p><p> marker.openInfoWindowTabsHtml(infoTabs);</p> <p>}</p><p><b>Figure 17:</b> Insertimages into the balloon by using the <img> HTML element.</p><p> </p><p><img width="333" height="412" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image022.gif"><br><b>Figure 18:</b> Displaying an image in amarker balloon.</p><p> </p><h3>Searching for Locations</h3><p> Another useful feature to add to Google Maps is theability to search for locations. To demonstrate how, add the following HTML inthe Source View of Default.aspx: </p><p> </p><p><ContentTemplate> </p><p> <asp:Button ID="btnAddMarker"runat="server"</p> <p> Text="AddMarker" Width="104px"</p> <p> OnClientClick="AddMarker()" /> </p><p><b> <br /> </b></p><p><b> Enter address to search: </b></p><p><b> <asp:TextBox ID="txtAddress"runat="server"> </b></p><p><b> </asp:TextBox> </b></p><p><b> <asp:Button ID="btnSearch"runat="server" Text="Search" </b></p><p><b> Width="104px"OnClientClick="findAddress()" /> </b></p><p></ContentTemplate> </p><p> </p><p> Next, declare the geocoder object as follows: </p><p> </p><p><script type="text/javascript"></p> <p>var map = null; </p><p><b>var geocoder = newGClientGeocoder();</b></p><p> </p><p> Then, define the findAddress JavaScript function, as shownin Figure 19. </p><p> </p><p>function findAddress() {</p><p> //---get the address tosearch for---</p><p> var address =document.forms[0].txtAddress.value; </p><p> geocoder.getLatLng(address, </p><p> function(point) {</p><p> //---if address isnot found---</p><p> if (!point) {</p><p> alert(address +" not found"); </p><p> } else {</p><p> //---addressfound---</p><p> map.setCenter(point, 13); </p><p> //---create a newmarker---</p><p> var marker = newGMarker(point); </p><p> //---close themarker if it is clicked---</p><p> GEvent.addListener(marker, "click", function() {</p><p> if (marker) {</p><p> //---closethe balloon---</p><p> map.closeInfoWindow();</p><p> //---removethe marker---</p><p> map.removeOverlay(marker); </p><p> }</p><p> });</p><p> //---add themarker---</p><p> map.addOverlay(marker); </p><p> //---display theaddress---</p><p> marker.openInfoWindowHtml("Found: " + address); </p><p> } </p><p> } </p><p> ); </p><p>}</p><p><b>Figure 19:</b> Definethe findAddress JavaScript function.</p><p> </p><p> The findAddress function searches for a specified addressusing the getLatLng method from the geocoder object. Because the search maytake some time, you need to define a function so it can process the returningresult later. The found address is returned as a point object, which you willuse to add a marker on the map. In addition, you ll display in the markerballoon a message indicating the found location. Figure 20 shows the markeradded to the map when I searched for Empire State Building .</p><p> </p><p><img width="333" height="413" src="https://www.itprotoday.com/content/legacy/images/asp200710wl_f_image024.gif"><br><b>Figure 20:</b> Searching for the addressof the Empire State Building.</p><p> </p><h3>Conclusion</h3><p> You ve now seen the basics of how to get started with theGoogle Maps API. The Google Maps API offers much more than what I can possiblydescribe in this space. As you become comfortable with it, check out thedocumentation and explore the rest of what the API offers. In Part II, you lllearn how to geo-tag your photos using Google Maps.</p><p> </p><p> <i>The source code accompanyingthis article is available for download. </i></p><p> </p><p><b>Wei-Meng Lee</b> (<a href="https://weimenglee.blogspot.com/">http://weimenglee.blogspot.com</a>) is aMicrosoft MVP and founder of Developer Learning Solutions (<a href="https://www.learn2develop.net/">http://www.learn2develop.net</a>), atechnology company specializing in hands-on training on the latest Microsofttechnologies. He is an established developer and trainer specializing in .NETand wireless technologies. Wei-Meng speaks regularly at internationalconferences and has authored and co-authored numerous books on .NET, XML, andwireless technologies. He writes extensively on topics ranging from .NET to MacOS X. He is also the author of.NET CompactFramework Pocket Guide, ASP.NET 2.0: ADeveloper s Notebook (both from O Reilly Media, Inc), and Programming Sudoku (Apress).</p><p> </p><p> </p><p> </p>
Read more about:
Alphabet Inc.About the Author
You May Also Like