0

I'm trying to make a program that builds up a boundary area on Google Maps API v3 from given points stored in a database. I made this work in PHP however couldn't run checks to see if a point is within the bounds or not.

I've re-created it in JavaScript however I've hit a wall with showing the points. I've pulled the points back in and there echoed as a a JS variable:

Example:
var boundArray =  ["52.6,1.19","52.7,1.20","52.7,1.19","52.6,1.20"];

I'm trying to run through the array and build up the 'path' attribute for the polygon however it wont allow me to run a for loop within the array and I cannot construct this in an alternative method.

function grabPoints() {
    var catchmentCoords = [
        for(var i=0; i<(boundArray.length-1); i++){
            new google.maps.LatLng(boundArray[$i]),
        }
        new google.maps.LatLng(boundArray[boundArray.length])
    ];
}

The function above should build a list of points in the variable as shown below which is used to show all points at once.

var catchmentCoords = [
    new google.maps.LatLng(52.6,1.19),
    new google.maps.LatLng(52.7,1.20),
    new google.maps.LatLng(52.7,1.19),
    new google.maps.LatLng(52.6,1.20)
];

If it helps the attribute is intended to be used within the polygon function for the API.

catchmentArea = new google.maps.Polygon({
    paths: catchmentCoords
});

Additionally if there is a nicer way to search if a lat/long is inside a polygon this would be appreciated.

geocodezip
  • 158,664
  • 13
  • 220
  • 245
tgrobinson
  • 233
  • 3
  • 15
  • Can u create js fiddle for your eg – Nouphal.M Dec 27 '13 at 16:53
  • You have a logic error in your for loop. `for(var i=0; i<(boundArray.length-1); i++){` will loop one less times than you want. Should just be `for(var i=0; i < boundArray.length; i++){` – duncan Dec 27 '13 at 17:29

2 Answers2

1

A google.maps.LatLng takes 2 numbers as arguments, not a string representation of 2 numbers separated by a comma.

function grabPoints() {
    var catchmentCoords = [];
    for(var i=0; i<(boundArray.length); i++){
        var coordsStr = boundArray[i];
        var coords = coordsStr.split(",");
        catchmentCoords.push(new google.maps.LatLng(coords[0],coords[1])));
    }
}

working example

geocodezip
  • 158,664
  • 13
  • 220
  • 245
0

This is basic Javascript.

Try something like this:

function grabPoints() {
    var catchmentCoords = [];
    for(var i=0; i<boundArray.length; i++){
        catchmentCoords.push(new google.maps.LatLng(parseFloat(boundArray[i])));
    }
    var catchmentArea = new google.maps.Polygon({
        paths: catchmentCoords
    });
}
duncan
  • 31,401
  • 13
  • 78
  • 99