Capturing click on a specific area of Google Maps (Gmaps API)

Asked

Viewed 236 times

0

Hello,

I am developing a web application that makes use of the Google Maps API to map plots of farms, and highlight them with different colors according to the level of a particular pest.

I need to capture the user click inside the selected area as shown in the image below, I found some algorithms able to calculate the click location but I’m having doubts to apply it. I am using Javascript.

When clicking within the area, I want to do a certain action, my question is: how to capture this click, using the Google Maps API, within a specific area mapped by latitude and longitude?

A imagem mostra o mapeamento por pontos de coordenada feito usando google Earth

Algorithm I found to calculate the point within the area:

window.isPointInPolygon = function(pontoClique, arrayCoordenadas) {
  var intersectCount = 0;
  for (var j = 0; j < arrayCoordenadas.size() - 1; j++) {
    if (rayCastIntersect(pontoClique, arrayCoordenadas.get(j), arrayCoordenadas.get(j + 1))) {
        intersectCount++;
    }
  }
  return ((intersectCount % 2) == 1); // odd = inside, even = outside;
}

var rayCastIntersect = function(pontoClique, LatLngVertA, LatLngVertB) {
  var aY = LatLngVertA.lat;
  var bY = LatLngVertB.lat;
  var aX = LatLngVertA.lng;
  var bX = LatLngVertB.lng;
  var pY = pontoClique.lat;
  var pX = pontoClique.lng;

  if ((aY > pY && bY > pY) || (aY < pY && bY < pY) || (aX < pX && bX < pX)) {
    return false; // a and b can't both be above or below pt.y, and a or
    // b must be east of pt.x
  }

  var m = (aY - bY) / (aX - bX); // Rise over run
  var bee = (-aX) * m + aY; // y = mx + b
  var x = (pY - bee) / m; // algebra is neat!
  return x > pX;
  }

Note: The algorithm was in Java, I adapted it to Javascript which is what I need.

Sincerely yours;

1 answer

0

Hello, I register an event addListener('click', function); in the plot, the Gmaps API checks to see if the click was done in the highlighted area. (see addListener here)

var area = new google.maps.Polygon(area_opts);
area.setMap(map);
//(...)
area.addListener('click', doSomething);

function doSomething(){
console.log('Você clicou no talhão');
}

  • 1

    Is that a question or are you answering the topic?

  • This is an answer to the topic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.