Google Maps V3: Re-Draw Google Map Route with updated Latitide and Longitude

Last Reply 10 months ago By dharmendr

Posted 10 months ago
</body>
</html><script type="text/javascript">

    var mydata = JSON.parse(data);

    var markers = mydata.map(function (location) {
        return {
            title: location.yer,
            lat: location.lat,
            lng: location.lng   
        };
    });
    //alert(markers);
    //alert(mydata);

    $(document).ready(function () {

        var socket = io.connect("http://localhost:1234");
        socket.emit("Koordinatlar", mydata);
        socket.emit("cenk", markers);

        socket.on("test", function (data) {
            alert(data);

        });

        //0. eleman min değer, 1. eleman max değer. (dizide)
        var max_min_degerler = [];

        $("#btnSend").click(function () {
            max_min_degerler[0] = $("#min").val();
            max_min_degerler[1] = $("#max").val();

            socket.emit("Sorgu", max_min_degerler);

        });

    });

    window.onload = function () {
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        var infoWindow = new google.maps.InfoWindow();
        var lat_lng = new Array();
        var latlngbounds = new google.maps.LatLngBounds();
        for (i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            lat_lng.push(myLatlng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.title
            });
            latlngbounds.extend(marker.position);
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.description);
                    infoWindow.open(map, marker);
                });
            })(marker, data);
        }
        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);

        //***********ROUTING****************//

        //Intialize the Path Array
        var path = new google.maps.MVCArray();

        //Intialize the Direction Service
        var service = new google.maps.DirectionsService();

        //Set the Path Stroke Color
        var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });

        //Loop and Draw Path Route between the Points on MAP
        for (var i = 0; i < lat_lng.length; i++) {
            if ((i + 1) < lat_lng.length) {
                var src = lat_lng[i];
                var des = lat_lng[i + 1];
                path.push(src);
                poly.setPath(path);
                service.route({
                    origin: src,
                    destination: des,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                }, function (result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                            path.push(result.routes[0].overview_path[i]);
                        }
                    }
                });
            }
        }
    }
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
</body>
</html>

I have a code above in the html section. This code reads the coordinates from the json file and prints it on google map (red line). I used node.js on the server side.

The following code:

var socket = io.connect("http://localhost:1234");
socket.emit("cenk", markers);
socket.on("test", function (data) {
    alert(data);
});

At first I extract the data from a file located in the same place as the project and display it as a road between google map te (red line). I am sending the coordinates (given by socket.io) to the server side and returning that data to the client after I have done some operations on that data.

backtracking works fine. In the small code I share above, I can see the window of the data browser called node.js using the alert function (the data variable holds the data from the server and I can see it in the window). But I want to rename the node.js coordinates and update Google map again. (or it may be to override the map, in short whatever the path is). For example, the data coming from node.js would be:

[{"title":"x","lat":"41.01766","lng":"28.97438"},{"title":"y","lat":"41.05877","lng":"28.92305"}]

I want to draw this one again in the same html (red line) as it will be the path between them. What can I do for it?

You are viewing reply posted by: dharmendr 10 months ago.
Posted 10 months ago

Hi Shalaman,

Check this example. Now please take its reference and correct your code.

Here i am just showing an example. The map will be populate with some initial data based on the global JavaScript Array on load. Then on button click i have changed the JavaScript Array with updated value and redraw the map based on the updated value.

You need to modified your code based on your datareturned by nodejs as per your requirement.

HTML

<script type="text/javascript">
    // Initialize map data.
    var mydata = [];
    mydata = [{ "title": 'Alibaug', "lat": '18.641400', "lng": '72.872200' },
                    { "title": 'Mumbai', "lat": '18.964700', "lng": '72.825800' },
                    { "title": 'Pune', "lat": '18.523600', "lng": '73.847800'}];
    //var mydata = JSON.parse(data);
    window.onload = function () {
        DrawRoute();
    }

    $(document).ready(function () {
        $("#btnSend").click(function () {
            // Reassign map data with updated value.
            mydata = [{ "title": "x", "lat": "41.01766", "lng": "28.97438" }, { "title": "y", "lat": "41.05877", "lng": "28.92305"}];
            // ReDraw Map.
            DrawRoute();
        });
    });

    function DrawRoute() {
        var markers = mydata.map(function (location) {
            return {
                title: location.title,
                lat: location.lat,
                lng: location.lng
            };
        });
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        var infoWindow = new google.maps.InfoWindow();
        var lat_lng = new Array();
        var latlngbounds = new google.maps.LatLngBounds();
        for (i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            lat_lng.push(myLatlng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.title
            });
            latlngbounds.extend(marker.position);
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.description);
                    infoWindow.open(map, marker);
                });
            })(marker, data);
        }
        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);

        //***********ROUTING****************//

        //Intialize the Path Array
        var path = new google.maps.MVCArray();

        //Intialize the Direction Service
        var service = new google.maps.DirectionsService();

        //Set the Path Stroke Color
        var poly = new google.maps.Polyline({ map: map, strokeColor: '#FD0000' });

        //Loop and Draw Path Route between the Points on MAP
        for (var i = 0; i < lat_lng.length; i++) {
            if ((i + 1) < lat_lng.length) {
                var src = lat_lng[i];
                var des = lat_lng[i + 1];
                path.push(src);
                poly.setPath(path);
                service.route({
                    origin: src,
                    destination: des,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                }, function (result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                            path.push(result.routes[0].overview_path[i]);
                        }
                    }
                });
            }
        }
    }
</script>
<div id="Div1" style="width: 300px; height: 300px">
</div>
<input type="button" id="Button1" value="Redraw" />

Screenshot