Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps, array + GLatLng + GPolyline

I am using the following code to group and show a list of ship positions on a map:

function configure_ship_polylines() {

    var shipPoints = new Array();

    // Group positions by ship
    for (var ScenarioPositionID in __data['scenarioPositions']) {

        var scenarioPosition = __data['scenarioPositions'][ScenarioPositionID];
        var key = "ShipID_" + scenarioPosition.ShipID;

        // Initialize if necessary
        if (shipPoints[key] == null) {
            shipPoints[key] = new Array();
        }

        var latLong = new GLatLng(scenarioPosition.Latitude, scenarioPosition.Longitude);

        // Append coordinates
        shipPoints[key].push(latLong);
    }


    // Loop through the grouped coordinates and add to map
    for (var key in shipPoints) {

        var points = shipPoints[key];
        var ShipID = key.substring(7);

        // Only add polygons with points.length > 1
        if (points.length > 1) {

            var shipPolyline = new GPolyline(points);

            //alert("Adding polyline: " + shipPolyline + " for ship: " + ShipID + " " + points + " " + typeof points);

            __mapItems['shipPolylines'][key] = shipPolyline;

            __map.addOverlay(shipPolyline);

        }
    }
}

What happens is that only one of the polylines are displayed on the map. The rest are invisible or aren't added at all (I'm not quite sure how to debug google maps to find out). I have used firebug extensively over and over again to debug this, but everything seems fine.

If I create polylines manually I can add them to the map and everything works fine. If I create markers on each point instead of polylines then the markers display fine at the correct places.

I'm getting kinda pissed at this because I have almost spent a full work day trying to figure out what the hell is going on. Any ideas?

like image 816
andrerav Avatar asked Nov 21 '25 14:11

andrerav


1 Answers

From your code, it looks like you add one GLatLng per shipPoints[key], so you never create enough points to make a line. In your first loop, you do:

shipPoints[key].push(latLong);

In your second loop you do

// points is a latlong
var points = shipPoints[key];
// create a polyline using one latlng
var shipPolyline = new GPolyline(points);
// add polyline to map
__map.addOverlay(shipPolyline);

If your goal, however, is to make a single polyline out of all the points, you need to create an array of many GLatLngs and then create one GPolyline after your loop ends. Then add that single polyline to the map.

By the way, you could do the whole thing in one loop.

like image 162
Harry Love Avatar answered Nov 24 '25 05:11

Harry Love



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!