2013-08-28 13 views
8

Come creare Polygon Geofence da più posizioni geografiche (valori lat lunghi). Anche come tracciare l'utente sta entrando in questa regione di geofence o uscendo da questa regione su Android.Geofencing Android (poligono)

risposta

12

Un geofence è semplicemente una matrice di punti lat/long che formano un poligono. Una volta che hai un elenco di punti lat/long, puoi usare un controllo point-inside-polygon per vedere se una posizione è all'interno del poligono.

Questo è il codice che ho usato nei miei progetti per eseguire i controlli point-in-poligono molto grandi poligoni concavi (20K + vertici):

public class PolygonTest 
{ 
    class LatLng 
    { 
     double Latitude; 
     double Longitude; 

     LatLng(double lat, double lon) 
     { 
      Latitude = lat; 
      Longitude = lon; 
     } 
    } 

    bool PointIsInRegion(double x, double y, LatLng[] thePath) 
    { 
     int crossings = 0; 

     LatLng point = new LatLng (x, y); 
     int count = thePath.length; 
     // for each edge 
     for (var i=0; i < count; i++) 
     { 
      var a = thePath [i]; 
      var j = i + 1; 
      if (j >= count) 
      { 
       j = 0; 
      } 
      var b = thePath [j]; 
      if (RayCrossesSegment(point, a, b)) 
      { 
       crossings++; 
      } 
     } 
     // odd number of crossings? 
     return (crossings % 2 == 1); 
    } 

    bool RayCrossesSegment(LatLng point, LatLng a, LatLng b) 
    { 
     var px = point.Longitude; 
     var py = point.Latitude; 
     var ax = a.Longitude; 
     var ay = a.Latitude; 
     var bx = b.Longitude; 
     var by = b.Latitude; 
     if (ay > by) 
     { 
      ax = b.Longitude; 
      ay = b.Latitude; 
      bx = a.Longitude; 
      by = a.Latitude; 
     } 
      // alter longitude to cater for 180 degree crossings 
     if (px < 0) { px += 360; }; 
     if (ax < 0) { ax += 360; }; 
     if (bx < 0) { bx += 360; }; 

     if (py == ay || py == by) py += 0.00000001; 
     if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false; 
     if (px < Math.min(ax, bx)) return true; 

     var red = (ax != bx) ? ((by - ay)/(bx - ax)) : float.MAX_VALUE; 
     var blue = (ax != px) ? ((py - ay)/(px - ax)) : float.MAX_VALUE; 
     return (blue >= red); 
    } 
} 

In termini di flusso di programma, si vuole uno sfondo servizio per fare gli aggiornamenti di posizione e quindi eseguire questo controllo sui dati del poligono lat/long per vedere se la posizione è all'interno.

+0

Geofence può anche essere scafo concavo. Ho scritto una classe PHP di geofence. – Bytemain

+0

Ah, ho scritto quello sbagliato no? Grazie per averlo evidenziato. – matthewrdev

+0

Questo è puro oro IMHO. Ha qualche limite pratico, carenze o inesattezze? Inoltre, questo algoritmo ha un nome? – LucasM