Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

Google Maps v3: check if point exists in polygon

I am looking to find a way of checking if a point exists inside a polygon in Google Maps v3 (JavaScript). I've searched everywhere and the only solutions I have found so far have been to do with getting the bounds of the polygon, but the code shown seems to just create a rectangle and keeps expanding its surface area to include all relevant points.

By the way, the reason I can't just use a big square i.e. getting a polygons bounds, is that I have bordering polygons on the map and they can not expand into each other's territory.

EDIT Following on from the reply below, I have tried implementing the example code using one of my existing polygons but it is just saying that it is not defined and I can't figure out why.

Here is my declaration:

myCoordinates = [
    new google.maps.LatLng(0.457301,-0.597382),
    new google.maps.LatLng(0.475153,-0.569916),
    new google.maps.LatLng(0.494379,-0.563049),
    new google.maps.LatLng(0.506738,-0.553436),
    new google.maps.LatLng(0.520470,-0.541077),
    new google.maps.LatLng(0.531456,-0.536957),
    new google.maps.LatLng(0.556174,-0.552063),
    new google.maps.LatLng(0.536949,-0.596008),
    new google.maps.LatLng(0.503991,-0.612488),
    new google.maps.LatLng(0.473780,-0.612488) ];

polyOptions = { 
    path: myCoordinates,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#0000FF",
    fillOpacity: 0.6 };

var rightShoulderFront = new google.maps.Polygon(polyOptions);
rightShoulderFront.setMap(map);

and here is where I am checking for the point:

var coordinate = selectedmarker.getPosition();
var isWithinPolygon = rightShoulderFront.containsLatLng(coordinate);
console.log(isWithinPolygon);

But it keeps coming up with the error: Uncaught ReferenceError: rightShoulderFront is not defined

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One algorithm to solve this is ray-casting. See an explanation here.

And you can find code implementing this for the Google Maps JS API V3 here.

HTH.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...