Search code examples
javagoogle-mapsgeolocation

Google API returning the server location, not user location


Hello so I though I was getting user location through this code but im actually getting the server's location, any idea how can I change it so I get the user location?

    public void geolocate() {
            try {

            GeolocationPayloadBuilder payloadBuilder = new GeolocationPayload.GeolocationPayloadBuilder();
            GeolocationPayload payload = payloadBuilder.createGeolocationPayload();
            //GeoApiContext context = new GeoApiContext.Builder().apiKey("my api key").build();
            // I guess the payload needs to be build in a different way but no clue how it should be :/
            GeolocationApiRequest req = (GeolocationApiRequest) GeolocationApi.geolocate(context, payload);

            GeolocationResult res = req.await();
            String location = res.location.toString();
            String[] latLngArray = location.split(",");
            com.google.maps.model.LatLng latLng = new com.google.maps.model.LatLng(Double.parseDouble(latLngArray[0]),
                    Double.parseDouble(latLngArray[1]));
            GeocodingApiRequest geoReq = GeocodingApi.reverseGeocode(context, latLng);
            GeocodingResult[] geoRes = geoReq.await();
            // Setting the user location for view
            System.out.println(geoRes[0].formattedAddress);
            origen.setValue(geoRes[0].formattedAddress);

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- " + e);
        }
        }

this is the dependency where im getting the objects from:

<dependency>
            <groupId>com.google.maps</groupId>
            <artifactId>google-maps-services</artifactId>
            <version>0.9.3</version>
</dependency>

hope somebody can help me with this, thanks in advance

EDIT:

I have been searching and found out how to build the payload with help of https://developers.google.com/maps/documentation/geolocation/intro#cell_tower_object

But I have a couple of question which is how will I get my users mac address to create the wifiAccessPoint and also where do I find info of cell towers in my city (Cali, Colombia)? Just an update will keep searching any help is appreciated..

@POST
@Path("/geolocate")
public String geolocate() {
    try {
        CellTower newCellTower = new CellTower.CellTowerBuilder().CellId(42).LocationAreaCode(415)
                .MobileCountryCode(310).MobileNetworkCode(410).Age(0).createCellTower();
        WifiAccessPoint newWifiAccessPoint = new WifiAccessPoint.WifiAccessPointBuilder()
                .MacAddress("00:25:9c:cf:1c:ac").createWifiAccessPoint();
        WifiAccessPoint newWifiAccessPoint2 = new WifiAccessPoint.WifiAccessPointBuilder()
                .MacAddress("00:25:9c:cf:1c:ad").createWifiAccessPoint();

        GeolocationPayloadBuilder payloadBuilder = new GeolocationPayload.GeolocationPayloadBuilder()
                .HomeMobileCountryCode(310).HomeMobileNetworkCode(410).RadioType("gsm").Carrier("Vodafone")
                .ConsiderIp(false).AddCellTower(newCellTower).AddWifiAccessPoint(newWifiAccessPoint)
                .AddWifiAccessPoint(newWifiAccessPoint2);
        GeolocationPayload payload = payloadBuilder.createGeolocationPayload();
        GeoApiContext context = new GeoApiContext.Builder().apiKey("my api key")
                .build();

        GeolocationApiRequest req = (GeolocationApiRequest) GeolocationApi.geolocate(context, payload);

        GeolocationResult res = req.await();
        String location = res.location.toString();
        String[] latLngArray = location.split(",");
        com.google.maps.model.LatLng latLng = new com.google.maps.model.LatLng(Double.parseDouble(latLngArray[0]),
                Double.parseDouble(latLngArray[1]));
        GeocodingApiRequest geoReq = GeocodingApi.reverseGeocode(context, latLng);
        GeocodingResult[] geoRes = geoReq.await();
        // Setting the user location for view
        return geoRes[0].formattedAddress;

    } catch (Exception e) {
        System.out.println("Exception in NetClientGet:- " + e);
    }
    return "XD";
}

Solution

  • The Geolocation API of Google Maps Platform is not intended for getting user location, what I can suggest is that you use the HTML5 Geolocation instead, there's also a sample of that in the Google Maps Platform documentation. But please note that this is not supported by Google as this is using HTML5 Geolocation and not Google APIs, if you wish to get the address of the user location as well, you may Geocode the coordinates that will be returned by the HTML5 Geolocation. You may see the sample below (without the Geocoding function). Here's a working sample - https://jsfiddle.net/w2sad5pn/

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
    
          infoWindow.setPosition(pos);
          infoWindow.setContent('Location found.');
          infoWindow.open(map);
          map.setCenter(pos);
        }, function() {
          handleLocationError(true, infoWindow, map.getCenter());
        });
      } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
      }
    }