Saturday, December 29, 2012

how to show Google Static Map using javascript

We often use Google Static Map to show office location or shop location. Moreover, it is in wide use to display the direction from one place to another. This post will explain you the simple way how to use Javascript for displaying dynamic Google Map using Google Static Maps API V2.
Google Static Map using Javascript
First, it needs the following script in <head> tag.
<script type="text/javascript">
    var position = new Object();
    function showPosition(position) {
        var latlon = position.latitude + "," + position.longitude;
        var imgUrl = "http://maps.googleapis.com/maps/api/staticmap?center=" +
            latlon + "&zoom=16&size=500x400&sensor=false";
        document.getElementById("mapholder").innerHTML = "<img src='" + imgUrl + "' />";
    }
    window.onload = function () {
        position.latitude = 13.745674;
        position.longitude = 100.53422;
        showPosition(position);
    }
    function showMap() {
        position.latitude = document.getElementById("txtLat").value;
        position.longitude = document.getElementById("txtLon").value;
        showPosition(position);
    }
</script>
Secondly, create the image container and controls in <body> tag as below:
<form id="form1" runat="server">
    <div id="mapholder">
    </div>
    <div>
        <asp:Label ID="Label1" runat="server" Text="Latitude :"></asp:Label>
        <asp:TextBox ID="txtLat" runat="server" Text="13.715236" ClientIDMode="Static"></asp:TextBox><br />
        <asp:Label ID="Label2" runat="server" Text="Longitude:"></asp:Label>
        <asp:TextBox ID="txtLon" runat="server" Text="100.591233" ClientIDMode="AutoID"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Show Map" onclientclick="showMap();return false;" />
    </div>
</form>
That's it. When it run, it shows one location and then press "Show Map" button to see another place.
This post is the last one for this year. See you next year. Thank.

No comments:

Post a Comment