Thursday, April 19, 2012

Google Maps : Create Marker and Draw Line Runtime

in this demo user can add a marker by simply click on map

and line is automatically draw by map between marker

also marker is Draggable.

Demo image



Code


<!--
     Created By : Yogesh Prajapati
           Date : 03 April 2011
-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title> Search Demo </title>
        <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA" type="text/javascript"></script>
      

        <script type="text/javascript">
            var map;
            var secondLastMarker = null
            var lastMarker = null;
           
            function initialize() {
               
                if (GBrowserIsCompatible()) {
                   
                    map = new GMap2(document.getElementById("map_canvas"));
                    map.setCenter(new GLatLng(23.450, 72.483), 11);
                    map.addControl(new GSmallMapControl());
                   
                    GEvent.addListener(map, "click", function(overlay, latLng) {
                        var marker = new GMarker(latLng,{draggable: true});
                        map.addOverlay(marker);
                        if(lastMarker == null){
                            lastMarker = latLng;
                        }else if(secondLastMarker == null){
                            secondLastMarker = lastMarker;
                            lastMarker = latLng;
                            drawLine(map,secondLastMarker,lastMarker);
                        }else{
                            secondLastMarker = lastMarker;
                            lastMarker = latLng;
                            drawLine(map,secondLastMarker,lastMarker);
                        }
                       });
                }
            }
           
            function drawLine(map,firstPoint,LastPoint){
                var polyline = new GPolyline([secondLastMarker,lastMarker
                                              ], "#ff0000", 5);
                    map.addOverlay(polyline);
            }
                       
        </script>
    </head>

    <body onload="initialize()" onunload="GUnload()" style="background-color:aliceblue">
           <div id="map_canvas" style="width: 100%; height: 550px;"></div>
        Demo Created By : <b>Yogesh Prajapati</b><br/>
    </body>

</html>

Note:

Line is just polyLine if you want to draw path between them than you need to do something different
this is just for demo purpose.

No comments:

Post a Comment

Post a Comment

Disqus for yogi's talk

comments powered by Disqus