Geolocation example for Processing ;)

This is a simple example to get geoLocation in Processing JAVA MODE on “windows / linux / macosx / andorid”.

import java.net.*;
import java.io.*;
void setup(){
    String[] l = geolocation();
    for(String s : l){
        println(s);
    }
}
void draw(){
    
}
String[] geolocation(){
    StringList l = new StringList();
    String[] data = null;
    Socket sock = null;
    BufferedReader bufRead = null;
    try{
        sock = new Socket("ip-api.com", 80);
        //Instantiates a new PrintWriter passing in the sockets output stream
        PrintWriter wtr = new PrintWriter(sock.getOutputStream());
        //Prints the request string to the output stream
        wtr.println("GET /json HTTP/1.0");
        wtr.println("");
        wtr.flush();
                    
        //Creates a BufferedReader that contains the server response
        bufRead = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        String outStr = "";
                    
        //Prints each line of the response 
        while((outStr = bufRead.readLine()) != null){
            l.append(outStr);
        }
            
        //Closes out buffer and writer
        bufRead.close();
        wtr.close();
        
        // parse output..
        for(String s : l){
            if(s.contains("{")){
                String s1 = s.substring(1);
                String s2 = s1.substring(0, s1.length()-1);
                data = split(s2, ",");
            }
        }
        
    }catch(Exception e){
        println(e);
    }
    
    return data;
}
2 Likes

My output for this program are this:

“status”:“success”
“country”:“Spain”
“countryCode”:“ES”
“region”:“CT”
“regionName”:“Catalonia”
“city”:“Barcelona”
“zip”:“08005”
“lat”:41.3891
“lon”:2.1611
“timezone”:“Europe/Madrid”
“isp”:“Xtratelecom”
“org”:“XFERA Moviles S.A.”
“as”:“AS15704 XTRA TELECOM S.A.”
“query”:“95.169.234.191”

Very util for rankings online with “country” tag etc etc…

1 Like

Very nice, but in my case it missed the city.
It should be Recife. instead of Caruaru. How cume?

In any case, this service is interesting, although it may have a small margin of error. :wink:

1 Like

Because it simply loads the data from https://ip-api.com/ (scroll down) based on your current IP.

If the IP address of your internet service provider or proxy is not in the same city as you then the geolocation will not be correct.

1 Like