poly line colour swap on mouse over using google maps JavaScript API


poly line on google maps works as expected. but would like to swap poly line colour between multiple colours on mouse over

let us say a poly line [link] between two locations, if there is some problem with poly line [link] it sets to red colour, if there is latency or congestion with poly line [link] it sets to orange colour, but by default it is in green colour. given in our world map it has so many poly line [links between various locations], would like to give operator to highlight the poly line [link] with pink colour that he looking into

is there a way to extract the current stroke colour code [red, orange or green] of a poly line when mouse over and change it with pink colour, so when mouse out, restore it to active colour [red, orange or green]?

sample code:


        <title>Simple Polylines</title>
        <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script src="./index.js"></script>
        <div id="map"></div>
        <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap&v=weekly" async></script>


#map { height: 100%; }

html, body { height: 100%; margin: 0; padding: 0; }


function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {zoom: 3, center: { lat: 0, lng: -180 }, mapTypeId: "terrain",});
    const flightPlanCoordinates = [ { lat: 37.772, lng: -122.214 }, { lat: 21.291, lng: -157.821 }, { lat: -18.142, lng: 178.431 }, { lat: -27.467, lng: 153.027 },];
    const flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2,});
    google.maps.event.addListener(flightPath, "mouseover", function(event) { this.setOptions({strokeColor: "#FF1493", }); });
    google.maps.event.addListener(flightPath, "mouseout", function(event) { this.setOptions({strokeColor: "#008000", }); });


You can use the polyline’s strokeColor property – and extract it in the listener and use it later: lastStrokeColor = this.strokeColor;.

Sample code based on your example above: https://jsfiddle.net/jdtvqLrx/2/

Answered By – Moshe Jonathan Gordon Radian

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.