-
In this topic we saw how to create a Geofence code in JavaScript, I recommend its reading:
Geofence. Check if a point is inside a polygon. JavaScript. Map -
Now we are going to see some Java code to create an extension.
-
We will adapt this code:
https://www.algorithms-and-technologies.com/point_in_polygon/java -
Tutorial in Spanish and Extension:
App Inventor.Geofence. JavaScript. Extensión. Punto dentro o fuera de un polígono. Mapa. Coordenadas. -
Here we have it:
KIO4_Geofence.java
package com.KIO4_Geofence;
// © Juan Antonio Villalpando
// http://kio4.com/appinventor/251_exten_geofence_javascript.htm
// 2022/05/04
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.runtime.*;
@DesignerComponent(version = 1,
description = "Geofence. Find out if a point is inside a polygon. "
+ "Juan Antonio Villalpando - KIO4.COM ",
category = ComponentCategory.EXTENSION,
nonVisible = true,
iconName = "")
@SimpleObject(external = true)
public class KIO4_Geofence extends AndroidNonvisibleComponent implements Component {
private ComponentContainer container;
public KIO4_Geofence(ComponentContainer container) {
super(container.$form());
this.container = container;
}
////////////////////////// FUNCION /////////////////////////
@SimpleFunction(description = "Example String polygon: [[36.53,-6.27],[36.51,-6.28],[36.54,-6.29],[36.55,-6.22]]. Return boolean.")
public boolean Geofence(String polygon, String latitude, String longitude){
float point[] = new float[2];
point[0] = Float.valueOf(latitude);
point[1] = Float.valueOf(longitude);
int puntos = -1; // Vertices del poligono.
for (int i = 0; i < polygon.length(); i++) {
if (polygon.charAt(i) == '[') {puntos++;}}
float polygonF[][] = new float[puntos][puntos]; // Array float 2 dimensiones.
polygon = polygon.replace("[", "").replace("]", "");
String[] polygonArray = polygon.split(",");
for (int i = 0; i < puntos; i++) {
polygonF[i][0] = Float.valueOf(polygonArray[i*2]);
polygonF[i][1] = Float.valueOf(polygonArray[i*2+1]);
}
boolean odd = false;
for (int i = 0, j = polygonF.length - 1; i < polygonF.length; i++) {
if (((polygonF[i][1] > point[1]) != (polygonF[j][1] > point[1]))
&& (point[0] < (polygonF[j][0] - polygonF[i][0]) * (point[1] - polygonF[i][1]) / (polygonF[j][1] - polygonF[i][1]) + polygonF[i][0])) {
odd = !odd;
}
j = i;
}
return odd;
}
} // ==> FIN
The code returns a boolean true or false.