Google Map Polyline

<script type="text/javascript">
var map;
var markers = [];
var path = [];

$(function () {

    var opts = {
        zoom: 10,
        center: { lat: 23.564587, lng: 90.569874 },
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), opts);



    $('#AttendanceSearch').click(function (e) {
        e.preventDefault();
               

        var newMarker = {};
        newMarker.Latitude = 24.8594959;
        newMarker.Longitude = 89.3631192;
        newMarker.Accuracy = 20.0;
        newMarker.MarkerName = 'hi';
        markers.push(newMarker);
        path.push(new google.maps.LatLng(24.8594959, 89.3631192));

        var markerTwo = {};
        markerTwo.Latitude = 23.9246227;
        markerTwo.Longitude = 90.7130343;
        markerTwo.Accuracy = 20.0;
        markerTwo.MarkerName = 'hello';

        markers.push(markerTwo);
        path.push(new google.maps.LatLng(23.9246227, 90.7130343));

        setArrows = new ArrowHandler();

        //Looping markers array--->
        markers.forEach(function (markerInfo, index) {
            //marker object --->
            var marker = new google.maps.Marker({
                name: markerInfo.MarkerName,
                position: { lat: markerInfo.Latitude, lng: markerInfo.Longitude },
                map: map,
                title: markerInfo.MarkerName
            });
            //marker object ---<

            marker.addListener('click', function () {
                var contentString = "Hello Bro";


                var infowindow = new google.maps.InfoWindow({
                    content: contentString
                });

                infowindow.open(map, marker);
            });

        });
        //Looping markers array ----<

        createPoly(path, "midline");
    });
</script>


<script type="text/javascript">
    //<![CDATA[

    /**
     * Based on code provided by Mike Williams
     * http://econym.org.uk/gmap/arrows.htm
     * Improved and transformed to v3
    */

    var setArrows;


    function ArrowHandler() {
        this.setMap(map);
        // Markers with 'head' arrows must be stored
        this.arrowheads = [];
    }
    // Extends OverlayView from the Maps API
    ArrowHandler.prototype = new google.maps.OverlayView();

    // Draw is inter alia called on zoom change events.
    // So we can use the draw method as zoom change listener
    ArrowHandler.prototype.draw = function () {

        if (this.arrowheads.length > 0) {
            for (var i = 0, m; m = this.arrowheads[i]; i++) {
                m.setOptions({ position: this.usePixelOffset(m.p1, m.p2) });
            }
        }
    };


    // Computes the length of a polyline in pixels
    // to adjust the position of the 'head' arrow
    ArrowHandler.prototype.usePixelOffset = function (p1, p2) {

        var proj = this.getProjection();
        var g = google.maps;
        var dist = 12; // Half size of triangle icon

        var pix1 = proj.fromLatLngToContainerPixel(p1);
        var pix2 = proj.fromLatLngToContainerPixel(p2);
        var vector = new g.Point(pix2.x - pix1.x, pix2.y - pix1.y);
        var length = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
        var normal = new g.Point(vector.x / length, vector.y / length);
        var offset = new g.Point(pix2.x - dist * normal.x, pix2.y - dist * normal.y);

        return proj.fromContainerPixelToLatLng(offset);
    };


    // Returns the triangle icon object
    ArrowHandler.prototype.addIcon = function (file) {
        var g = google.maps;
        var icon = {
            url: "http://www.google.com/mapfiles/" + file,
            size: new g.Size(24, 24), anchor: new g.Point(12, 12)
        };
        return icon;
    };

    // Creates markers with corresponding triangle icons
    ArrowHandler.prototype.create = function (p1, p2, mode) {
        var markerpos;
        var g = google.maps;
        if (mode == "onset") markerpos = p1;
        else if (mode == "head") markerpos = this.usePixelOffset(p1, p2);
        else if (mode == "midline") markerpos = g.geometry.spherical.interpolate(p1, p2, .5);

        // Compute the bearing of the line in degrees
        var dir = g.geometry.spherical.computeHeading(p1, p2).toFixed(1);
        // round it to a multiple of 3 and correct unusable numbers
        dir = Math.round(dir / 3) * 3;
        if (dir < 0) dir += 240;
        if (dir > 117) dir -= 120;
        // use the corresponding icon
        var icon = this.addIcon("dir_" + dir + ".png");
        var marker = new g.Marker({
            position: markerpos,
            map: map, icon: icon, clickable: false
        });
        if (mode == "head") {
            // Store markers with 'head' arrows to adjust their offset position on zoom change
            marker.p1 = p1;
            marker.p2 = p2;
            // marker.setValues({ p1: p1, p2: p2 });
            this.arrowheads.push(marker);
        }
    };

    ArrowHandler.prototype.load = function (points, mode) {
        for (var i = 0; i < points.length - 1; i++) {
            var p1 = points[i],
            p2 = points[i + 1];
            this.create(p1, p2, mode);
        }
    };


    // Draws a polyline with accordant arrow heads
    function createPoly(path, mode) {
        var poly = new google.maps.Polyline({
            strokeColor: "#0000ff",
            strokeOpacity: 0.8,
            strokeWeight: 3,
            map: map,
            path: path
        });

        setArrows.load(path, mode);
        return poly;
    }
</script>

Advertisements

Google map polyline

//API v2
var polyline = new GPolyline([
  new GLatLng(37.4419, -122.1419),
  new GLatLng(37.4519, -122.1519)],
  "#ff0000", 10);
map.addOverlay(polyline);

//API v3
var line = new google.maps.Polyline({
    path: [new google.maps.LatLng(37.4419, -122.1419), new google.maps.LatLng(37.4519, -122.1519)],
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 10,
    geodesic: true, //This line is optional
    map: map
});

Working with Google Map & Markers API v.2

<!--HTML -->
<div id="map"></div>
//JavaScript
<script src="https://maps.googleapis.com/maps/api/js?key=your_key"></script>
<script src="~/Areas/Admin/Assets2/markerclusterer.js"></script>

//Draw a google map without any marker on page load 
<script>
    var map;
    var markers = [];
    $(function () {
        var mapOptions = {
            center: { lat: 23.564587, lng: 90.569874 },
            zoom: 7,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
            map = new google.maps.Map(document.getElementById("map"), mapOptions);
    });
</script>


//--> Load marker data on search button click event 
<script>
    var $SubmitSearch = $('#SubmitSearch');
      
    //-->document.ready()
    $(function () {
        $SubmitSearch.click(function (e) {
            e.preventDefault();
            var fd = new FormData();

            $.ajax({
                type: 'POST',
                url: "../../../../Admin/Search/SearchResult/",
                processData: false,  // tell jQuery not to process the data
                contentType: false,   // tell jQuery not to set contentType
                data: fd,
                beforeSend: function () {
                    $SubmitSearch.attr('disabled', 'disabled');
                    $SubmitSearch.html('Working…');
                },
                success: function (response) {
                    deleteMarkers();
                    var hasData = response.hasdata;
                    if (hasData) {
                        var sites = JSON.parse(response.data);
                        var serialNo = 0;
                        //-->Looping the parsed data
                        sites.forEach(function (site, index) {
                            serialNo++;

                            var marker = new google.maps.Marker({
                                name: "12345",
                                position: { lat: site.Latitude, lng: site.Longitude },
                                map: map,
                                //icon: "../../Assets/images/google-map-markers/OutletMarker.png",
                                title: site.SiteId.toString()
                            });

                            marker.addListener('click', function () {

                                var contentString = '';

                                //-->Fetch default images from server
                                $.ajax({
                                    type: "POST",
                                    url: '../../../Common/GetMarkerDetails',
                                    contentType: "application/json; charset=utf-8",
                                    data: "{'siteId':'" + site.SiteId + "'}",
                                    dataType: "json",
                                    beforeSend: function () {

                                    },
                                    success: function (result) {
                                        contentString = '<img src="http://localhost:63716/Images/'+ result.ImageName +'" />';
                                    },
                                    error: function (request, status, error) {

                                    }
                                });
                                //<--- Fetch default images from server

                                var infowindow = new google.maps.InfoWindow({
                                    content: contentString
                                });

                                infowindow.open(map, marker);
                            });

                            markers.push(marker);
                        });
                        //<--Looping the parsed data


                        //-->Add marker clustering
                        var markerCluster = new MarkerClusterer(map, markers, {
                            gridSize: 40,
                            minimumClusterSize: 50
                        });
                        //-->Add marker clustering

                    }
                    else {
                        alert('Your search did not match with any record.')
                        $ShowMore.hide(); // No need to show anymore.
                        $('#resultCount').hide();
                    }

                },
                error: function (request, status, error) {
                    alert('Unknown error.');
                    $ShowMore.html('Error in loading data');
                    $ShowMore.attr('disabled', 'disabled');
                },
                complete: function () {
                    // ShowMarketResearchPlanningPopup();
                    $SubmitSearch.removeAttr('disabled');
                    $SubmitSearch.html('Search');
                }
            });

        });
        //<-- Submit Search

        // Sets the map on all markers in the array.
        function setMapOnAll(map) {
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(map);
            }
        }

        // Removes the markers from the map, but keeps them in the array.
        function clearMarkers() {
            setMapOnAll(null);
        }

        // Shows any markers currently in the array.
        function showMarkers() {
            setMapOnAll(map);
        }

        // Deletes all markers in the array by removing references to them.
        function deleteMarkers() {
            clearMarkers();
            markers = [];
        }

    });
    //<-- document.ready()
</script>
//<-- Load marker data on search button click event