com.google.maps.GeoApiContext Java Examples

The following examples show how to use com.google.maps.GeoApiContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LatLongFromLocation.java    From PokeMate with GNU General Public License v3.0 6 votes vote down vote up
public boolean parseLocation(String locationName){

        String ERROR_MESSAGE = "Couldn't find specified custom location, falling back to co-ordinates";
        if (locationName == null || locationName.equals("")) {
            System.out.println(ERROR_MESSAGE);
            return false;
        }

        GeoApiContext context = new GeoApiContext().setApiKey(GoogleApiKey);
        try {
            GeocodingResult[] request = GeocodingApi.newRequest(context).address(locationName).await();
            LatLng location = request[0].geometry.location;
            latitude = location.lat;
            longitude = location.lng;
            System.out.println("Found custom location to be: " + request[0].formattedAddress);
            return true;
        } catch (Exception e) {
            System.out.println(ERROR_MESSAGE);
            return false;
        }
    }
 
Example #2
Source File: DefaultPathService.java    From Real-Time-Taxi-Dispatch-Simulator with MIT License 6 votes vote down vote up
@Override
public String getCoordinatesFromGoogleAsPolyline(DirectionInput directionInput) {
    final GeoApiContext context = new GeoApiContext()
            .setApiKey(environment.getRequiredProperty("gpsSimmulator.googleApiKey"));
    final DirectionsApiRequest request = DirectionsApi.getDirections(
            context,
            directionInput.getFrom(),
            directionInput.getTo());

    try {
        DirectionsRoute[] routes = request.await();
        return routes[0].overviewPolyline.getEncodedPath();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example #3
Source File: MentorUtils.java    From lemonaid with MIT License 5 votes vote down vote up
public Point getLocationOfMentor(Mentor mentor) {
	GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyC9hT7x8gTBdXcTSEy6XU_EWpr_WDe8lSY");
	try {
		String address = "";
		if (mentor.getAddress1() != null && mentor.getAddress1().length() > 0 ) {
			address += (address.length() > 0 ? ", " : "") + mentor.getAddress1();
		}
		if (mentor.getAddress2() != null && mentor.getAddress2().length() > 0 ) {
			address += (address.length() > 0 ? ", " : "") + mentor.getAddress2();
		}
		if (mentor.getZip() != null && mentor.getZip().length() > 0 ) {
			address += (address.length() > 0 ? ", " : "") + mentor.getZip();
		}
		if (mentor.getCity() != null && mentor.getCity().length() > 0 ) {
			address += (address.length() > 0 ? ", " : "") + mentor.getCity();
		}
		if (mentor.getState() != null && mentor.getState().length() > 0 ) {
			address += (address.length() > 0 ? ", " : "") + mentor.getState();
		}
		if (mentor.getCountryId() != null && mentor.getCountryId().getName() != null && mentor.getCountryId().getName().length() > 0 ) {
			address += (address.length() > 0 ? ", " : "") + mentor.getCountryId().getName();
		}
		if (address.length() > 0) {
			GeocodingResult[] results =  GeocodingApi.geocode(context, address).await();
			return new Point(results[0].geometry.location.lat, results[0].geometry.location.lng);
		} else {
			log.error("Unable to geocode address of " + mentor.getFullName() + ": No address available");
			return null;
		}
	} catch (Exception e) {
		log.error("Unable to geocode address of " + mentor.getFullName() + ": " + e.toString());
		return null;
	}

}
 
Example #4
Source File: ConfigModule.java    From rox-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    bind(UsersApi.class)
            .toInstance(new UsersApi(context));
    bind(PoisApi.class)
            .toInstance(new PoisApi(context));
    bind(SQLiteOpenHelper.class)
            .annotatedWith(Names.named("GrayFoxDbHelper"))
            .toInstance(new GrayFoxDatabaseHelper(context));
    bind(GeoApiContext.class)
            .toInstance(new GeoApiContext().setApiKey(context.getString(R.string.google_maps_services_key)));
}
 
Example #5
Source File: MainActivity.java    From roads-api-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Geocodes a Snapped Point using the Place ID.
 */
private GeocodingResult geocodeSnappedPoint(GeoApiContext context, SnappedPoint point) throws Exception {
    GeocodingResult[] results = GeocodingApi.newRequest(context)
            .place(point.placeId)
            .await();

    if (results.length > 0) {
        return results[0];
    }
    return null;
}
 
Example #6
Source File: MainActivity.java    From roads-api-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves speed limits for the previously-snapped points. This method is efficient in terms
 * of quota usage as it will only query for unique places.
 *
 * Note: Speed Limit data is only available with an enabled Maps for Work API key.
 */
private Map<String, SpeedLimit> getSpeedLimits(GeoApiContext context, List<SnappedPoint> points)
        throws Exception {
    Map<String, SpeedLimit> placeSpeeds = new HashMap<>();

    // Pro tip: save on quota by filtering to unique place IDs
    for (SnappedPoint point : points) {
        placeSpeeds.put(point.placeId, null);
    }

    String[] uniquePlaceIds =
            placeSpeeds.keySet().toArray(new String[placeSpeeds.keySet().size()]);

    // Loop through the places, one page (API request) at a time.
    for (int i = 0; i < uniquePlaceIds.length; i += PAGE_SIZE_LIMIT) {
        String[] page = Arrays.copyOfRange(uniquePlaceIds, i,
                Math.min(i + PAGE_SIZE_LIMIT, uniquePlaceIds.length));

        // Execute!
        SpeedLimit[] placeLimits = RoadsApi.speedLimits(context, page).await();
        for (SpeedLimit sl : placeLimits) {
            placeSpeeds.put(sl.placeId, sl);
        }
    }

    return placeSpeeds;
}
 
Example #7
Source File: MainActivity.java    From roads-api-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Snaps the points to their most likely position on roads using the Roads API.
 */
private List<SnappedPoint> snapToRoads(GeoApiContext context) throws Exception {
    List<SnappedPoint> snappedPoints = new ArrayList<>();

    int offset = 0;
    while (offset < mCapturedLocations.size()) {
        // Calculate which points to include in this request. We can't exceed the APIs
        // maximum and we want to ensure some overlap so the API can infer a good location for
        // the first few points in each request.
        if (offset > 0) {
            offset -= PAGINATION_OVERLAP;   // Rewind to include some previous points
        }
        int lowerBound = offset;
        int upperBound = Math.min(offset + PAGE_SIZE_LIMIT, mCapturedLocations.size());

        // Grab the data we need for this page.
        LatLng[] page = mCapturedLocations
                .subList(lowerBound, upperBound)
                .toArray(new LatLng[upperBound - lowerBound]);

        // Perform the request. Because we have interpolate=true, we will get extra data points
        // between our originally requested path. To ensure we can concatenate these points, we
        // only start adding once we've hit the first new point (i.e. skip the overlap).
        SnappedPoint[] points = RoadsApi.snapToRoads(context, true, page).await();
        boolean passedOverlap = false;
        for (SnappedPoint point : points) {
            if (offset == 0 || point.originalIndex >= PAGINATION_OVERLAP) {
                passedOverlap = true;
            }
            if (passedOverlap) {
                snappedPoints.add(point);
            }
        }

        offset = upperBound;
    }

    return snappedPoints;
}
 
Example #8
Source File: MainActivity.java    From roads-api-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);

    SupportMapFragment mapFragment =
            (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    mContext = new GeoApiContext().setApiKey(getString(R.string.google_maps_web_services_key));
}
 
Example #9
Source File: MentorUtils.java    From lemonaid with MIT License 5 votes vote down vote up
public Point getPublicLocationOfMentor(Mentor mentor) {
	GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyC9hT7x8gTBdXcTSEy6XU_EWpr_WDe8lSY");
	try {
		String address = "";
		if (mentor.getAddress1() != null && mentor.getAddress1().length() > 0 && mentor.getAddress1Public()) {
			address += (address.length() > 0 ? ", " : "") + mentor.getAddress1();
		}
		if (mentor.getAddress2() != null && mentor.getAddress2().length() > 0 && mentor.getAddress2Public()) {
			address += (address.length() > 0 ? ", " : "") + mentor.getAddress2();
		}
		if (mentor.getZip() != null && mentor.getZip().length() > 0 && mentor.getZipPublic()) {
			address += (address.length() > 0 ? ", " : "") + mentor.getZip();
		}
		if (mentor.getCity() != null && mentor.getCity().length() > 0 && mentor.getCityPublic()) {
			address += (address.length() > 0 ? ", " : "") + mentor.getCity();
		}
		if (mentor.getState() != null && mentor.getState().length() > 0 && mentor.getStatePublic()) {
			address += (address.length() > 0 ? ", " : "") + mentor.getState();
		}
		if (mentor.getCountryId() != null && mentor.getCountryId().getName() != null && mentor.getCountryId().getName().length() > 0 && mentor.getCountryPublic()) {
			address += (address.length() > 0 ? ", " : "") + mentor.getCountryId().getName();
		}
		if (address.length() > 0) {
			GeocodingResult[] results =  GeocodingApi.geocode(context, address).await();
			return new Point(results[0].geometry.location.lat, results[0].geometry.location.lng);
		} else {
			log.error("Unable to geocode address of " + mentor.getFullName() + ": No address available");
			return null;
		}
	} catch (Exception e) {
		log.error("Unable to geocode address of " + mentor.getFullName() + ": " + e.toString());
		return null;
	}

}
 
Example #10
Source File: MapsServicesModule.java    From curiostack with MIT License 5 votes vote down vote up
@Provides
@Singleton
static GeoApiContext geoApiContext(MapsServicesConfig config) {
  return new GeoApiContext.Builder()
      .apiKey(config.getApiKey())
      .requestHandlerBuilder(new ArmeriaRequestHandler.Builder())
      .build();
}
 
Example #11
Source File: DefaultPathService.java    From Real-Time-Taxi-Dispatch-Simulator with MIT License 5 votes vote down vote up
@Override
public List<Point> getCoordinatesFromGoogle(DirectionInput directionInput) {

    final GeoApiContext context = new GeoApiContext()
            .setApiKey(environment.getRequiredProperty("gpsSimmulator.googleApiKey"));
    final DirectionsApiRequest request = DirectionsApi.getDirections(
            context,
            directionInput.getFrom(),
            directionInput.getTo());
    List<LatLng> latlongList = null;

    try {
        DirectionsRoute[] routes = request.await();

        for (DirectionsRoute route : routes) {
            latlongList = route.overviewPolyline.decodePath();
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    final List<Point> points = new ArrayList<>(latlongList.size());

    for (LatLng latLng : latlongList) {
        points.add(new Point(latLng.lat, latLng.lng));
    }

    return points;
}
 
Example #12
Source File: ListLandmarksGraph.java    From curiostack with MIT License 4 votes vote down vote up
@Produces
static ListenableFuture<PlacesSearchResponse> maybeSearchForLandmarks(
    S2LatLngRect viewport,
    GeoApiContext geoApiContext,
    S2CellUnion coveredCells,
    List<List<Landmark>> dbLandmarks) {
  // We find the first cell that is missing landmarks in the viewport to use as the center when
  // making the search request if needed.
  S2CellId firstCellMissingLandmarks =
      Streams.zip(
              Streams.stream(coveredCells),
              dbLandmarks.stream(),
              (cell, cellLandmarks) -> {
                if (cellLandmarks != null && !cellLandmarks.isEmpty()) {
                  return S2CellId.none();
                }
                return cell;
              })
          .filter(S2CellId::isValid)
          .findFirst()
          .orElse(S2CellId.none());

  if (firstCellMissingLandmarks.isValid()) {
    // At least one cell was covered - for now don't search again if any cells are covered.
    // For better logic, we will need to keep track of searched viewports some way..
    var response = new PlacesSearchResponse();
    response.results = EMPTY;
    return immediateFuture(response);
  }

  S2LatLng location = viewport.getCenter();
  int radius = (int) location.getEarthDistance(viewport.lo());

  CallbackListenableFuture<PlacesSearchResponse> callback = new CallbackListenableFuture<>();
  new NearbySearchRequest(geoApiContext)
      .location(new LatLng(location.latDegrees(), location.lngDegrees()))
      .radius(radius)
      .type(PlaceType.PARK)
      .setCallback(callback);
  return callback;
}
 
Example #13
Source File: SpeedLimitsWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public SpeedLimitsWorkitemHandler(GeoApiContext geoApiContext) {
    this.geoApiContext = geoApiContext;
}
 
Example #14
Source File: GoogleMapsAuth.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public GeoApiContext authorize(String apiKey) throws Exception {
    return new GeoApiContext.Builder()
            .apiKey(apiKey)
            .build();
}
 
Example #15
Source File: NfcDeviceFragment.java    From ESeal with Apache License 2.0 4 votes vote down vote up
private void processGoogleMapGeocodeLocation() {
    GeoApiContext geoApiContext = new GeoApiContext().setApiKey(App.GOOGLE_MAP_API_KEY);

    GeolocationPayload.GeolocationPayloadBuilder payloadBuilder = new GeolocationPayload.GeolocationPayloadBuilder()
            .ConsiderIp(false);

    Activity activity = getActivity();
    CellTower.CellTowerBuilder cellTowerBuilder = new CellTower.CellTowerBuilder()
            .CellId(NetUtil.getCellLocationCid(activity))
            .LocationAreaCode(NetUtil.getCellLocationLac(activity))
            .MobileCountryCode(Integer.parseInt(NetUtil.getTelephonyNetWorkOperatorMcc(activity)))
            .MobileNetworkCode(Integer.parseInt(NetUtil.getTelephonyNetWorkOperatorMnc(activity)));

    payloadBuilder.AddCellTower(cellTowerBuilder.createCellTower());

    if (NetUtil.isWifi(getContext())) {
        WifiAccessPoint.WifiAccessPointBuilder wifiAccessPointBuilder = new WifiAccessPoint.WifiAccessPointBuilder()
                .MacAddress(NetUtil.getWifiMacAddress(activity))
                .SignalStrength(NetUtil.getWifiRssi(activity));

        payloadBuilder.AddWifiAccessPoint(wifiAccessPointBuilder.createWifiAccessPoint());

        wifiAccessPointBuilder = new WifiAccessPoint.WifiAccessPointBuilder()
                .MacAddress(NetUtil.getWifiInfo(activity).getBSSID());


        payloadBuilder.AddWifiAccessPoint(wifiAccessPointBuilder.createWifiAccessPoint());
    }


    GeolocationApi.geolocate(geoApiContext, payloadBuilder.createGeolocationPayload())
            .setCallback(new PendingResult.Callback<GeolocationResult>() {
                @Override
                public void onResult(GeolocationResult result) {
                    Log.d(TAG, "onResult() returned: " + result.location.toString());
                }

                @Override
                public void onFailure(Throwable e) {
                    Log.d(TAG, "onFailure() returned: " + e.getMessage());
                }
            });
}
 
Example #16
Source File: GeocodingWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public GeocodingWorkitemHandler(GeoApiContext geoApiContext) {
    this.geoApiContext = geoApiContext;
}
 
Example #17
Source File: DirectionsWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public DirectionsWorkitemHandler(GeoApiContext geoApiContext) {
    this.geoApiContext = geoApiContext;
}
 
Example #18
Source File: TimezoneWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public TimezoneWorkitemHandler(GeoApiContext geoApiContext) {
    this.geoApiContext = geoApiContext;
}
 
Example #19
Source File: StaticMapsWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public StaticMapsWorkitemHandler(GeoApiContext geoApiContext) {
    this.geoApiContext = geoApiContext;
}
 
Example #20
Source File: ApiKey.java    From FXMaps with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Private constructor for creating an {@code ApiKey}
 * @param key
 */
private ApiKey(String key) {
    context = new GeoApiContext().setApiKey(key);
}
 
Example #21
Source File: ApiKey.java    From FXMaps with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Returns the {@link GeoApiContext}
 * @return
 */
GeoApiContext context() {
    return context;
}