March 07, 2007

Integrating Google Maps

Google Maps + Your web app = Simple

Working on a feature for my project and wanted to share how easily you can get Long + Lat using the Google Maps API.

First we need to get the presentation down. We'll be creating a popup div where you can type an address and a button that displays the location on the Google Map.

    <div id="selectgeo" runat="server" style="background-color: GreenYellow; border: solid 1px darkgreen;
position: absolute; left: 10px; top: 5px;">
Address:
<input id="txtAddr" type="text" />
<input id="btnfindgeo" type="button" value="Go" onclick="showAddress(document.getElementById('txtAddr').value); return false;" />
<input id="btndonegeo" type="button" value="Done" onclick="document.getElementById('selectgeo').style.display='none';" />
<div id="mappp" style="width: 270px; height: 175px">
</div>
</div>

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


REMEMBER to replace "yourkey" with your Google Maps API key. Get one here.

So we've got our Div: selectgeo, our Address box: txtAddr, our Button to find the location: btnfindgeo, our Done button: btndonegeo and finally our div which contains the map: mappp.

You can see btnfindgeo is wired up with a javascript function: showAddress. This is where the goods come from :) Onto the JavaScript!

var map;
var geocoder = new GClientGeocoder();

function loadGMap() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("mappp"));
map.addControl(new GSmallZoomControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4019, -122.1419), 13);
}
}

function showAddress(address) {
geocoder.getLatLng(address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
alert('['+ point.x + ', ' + point.y +']');
}
}
);
}

// Programatically load the map after onload.
var abo = document.getElementsByTagName("body");
if (abo != null) {
abo[0].onunload = GUnload;
abo[0].onload = loadGMap;
}


And you're done! Type in your address and see what happens.

Also the Google Maps API Documentation provides a TON of useful examples.

kick it on DotNetKicks.com

3 comments:

Alex said...

I'm do going to use this!! :)

Alex said...

Er, *so going to use this! :P

Aniela said...

what am i supposed to type in there? the geo data or the address?...frankly i'm typing both, and nothing happens...http://aniela.eu/api/api.html