com.google.maps.model.LatLng Java Examples

The following examples show how to use com.google.maps.model.LatLng. 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: RoadsApiIntegrationTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpeedLimitsWithLatLngs() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext(speedLimitsResponse)) {
    LatLng[] path =
        new LatLng[] {
          new LatLng(-33.865382, 151.192861),
          new LatLng(-33.865837, 151.193376),
          new LatLng(-33.866745, 151.19373),
          new LatLng(-33.867128, 151.19344),
          new LatLng(-33.867547, 151.193676),
          new LatLng(-33.867841, 151.194137),
          new LatLng(-33.868224, 151.194116)
        };
    SpeedLimit[] speeds = RoadsApi.speedLimits(sc.context, path).await();

    assertNotNull(Arrays.toString(speeds));
    assertEquals("/v1/speedLimits", sc.path());
    sc.assertParamValue(join('|', path), "path");
    assertEquals(7, speeds.length);

    for (SpeedLimit speed : speeds) {
      assertNotNull(speed.placeId);
      assertEquals(40.0, speed.speedLimit, 0.001);
    }
  }
}
 
Example #2
Source File: PlacesApiTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPlaceAutocompleteWithStrictBounds() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext(placesApiPlaceAutocomplete)) {
    SessionToken session = new SessionToken();
    PlacesApi.placeAutocomplete(sc.context, "Amoeba", session)
        .types(PlaceAutocompleteType.ESTABLISHMENT)
        .location(new LatLng(37.76999, -122.44696))
        .radius(500)
        .strictBounds(true)
        .await();

    sc.assertParamValue("Amoeba", "input");
    sc.assertParamValue("establishment", "types");
    sc.assertParamValue("37.76999000,-122.44696000", "location");
    sc.assertParamValue("500", "radius");
    sc.assertParamValue("true", "strictbounds");
    sc.assertParamValue(session.toUrlValue(), "sessiontoken");
  }
}
 
Example #3
Source File: PlacesApiTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindPlaceFromTextPoint() throws Exception {
  try (LocalTestServerContext sc =
      new LocalTestServerContext(findPlaceFromTextMuseumOfContemporaryArt)) {

    String input = "Museum of Contemporary Art Australia";

    PlacesApi.findPlaceFromText(sc.context, input, InputType.TEXT_QUERY)
        .fields(
            FindPlaceFromTextRequest.FieldMask.PHOTOS,
            FindPlaceFromTextRequest.FieldMask.FORMATTED_ADDRESS,
            FindPlaceFromTextRequest.FieldMask.NAME,
            FindPlaceFromTextRequest.FieldMask.RATING,
            FindPlaceFromTextRequest.FieldMask.OPENING_HOURS,
            FindPlaceFromTextRequest.FieldMask.GEOMETRY)
        .locationBias(new LocationBiasPoint(new LatLng(1, 2)))
        .await();

    sc.assertParamValue(input, "input");
    sc.assertParamValue("textquery", "inputtype");
    sc.assertParamValue("photos,formatted_address,name,rating,opening_hours,geometry", "fields");
    sc.assertParamValue("point:1.00000000,2.00000000", "locationbias");
  }
}
 
Example #4
Source File: PolylineEncoding.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
/** Encodes a sequence of LatLngs into an encoded path string. */
public static String encode(final List<LatLng> path) {
  long lastLat = 0;
  long lastLng = 0;

  final StringBuilder result = new StringBuilder();

  for (final LatLng point : path) {
    long lat = Math.round(point.lat * 1e5);
    long lng = Math.round(point.lng * 1e5);

    long dLat = lat - lastLat;
    long dLng = lng - lastLng;

    encode(dLat, result);
    encode(dLng, result);

    lastLat = lat;
    lastLng = lng;
  }
  return result.toString();
}
 
Example #5
Source File: PlacesApiTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindPlaceFromTextRectangular() throws Exception {
  try (LocalTestServerContext sc =
      new LocalTestServerContext(findPlaceFromTextMuseumOfContemporaryArt)) {

    String input = "Museum of Contemporary Art Australia";

    PlacesApi.findPlaceFromText(sc.context, input, InputType.TEXT_QUERY)
        .fields(
            FindPlaceFromTextRequest.FieldMask.PHOTOS,
            FindPlaceFromTextRequest.FieldMask.FORMATTED_ADDRESS,
            FindPlaceFromTextRequest.FieldMask.NAME,
            FindPlaceFromTextRequest.FieldMask.RATING,
            FindPlaceFromTextRequest.FieldMask.OPENING_HOURS,
            FindPlaceFromTextRequest.FieldMask.GEOMETRY)
        .locationBias(new LocationBiasRectangular(new LatLng(1, 2), new LatLng(3, 4)))
        .await();

    sc.assertParamValue(input, "input");
    sc.assertParamValue("textquery", "inputtype");
    sc.assertParamValue("photos,formatted_address,name,rating,opening_hours,geometry", "fields");
    sc.assertParamValue("rectangle:1.00000000,2.00000000|3.00000000,4.00000000", "locationbias");
  }
}
 
Example #6
Source File: PlacesApiTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryAutocompleteRequest() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext("{\"status\" : \"OK\"}")) {
    LatLng location = new LatLng(10, 20);
    PlacesApi.queryAutocomplete(sc.context, QUERY_AUTOCOMPLETE_INPUT)
        .offset(10)
        .location(location)
        .radius(5000)
        .language("en")
        .await();

    sc.assertParamValue(QUERY_AUTOCOMPLETE_INPUT, "input");
    sc.assertParamValue("10", "offset");
    sc.assertParamValue(location.toUrlValue(), "location");
    sc.assertParamValue("5000", "radius");
    sc.assertParamValue("en", "language");
  }
}
 
Example #7
Source File: PlacesApiTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPlaceAutocompleteRequest() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext("{\"status\" : \"OK\"}")) {
    SessionToken session = new SessionToken();
    LatLng location = new LatLng(10, 20);
    PlacesApi.placeAutocomplete(sc.context, "Sydney Town Hall", session)
        .offset(4)
        .origin(location)
        .location(location)
        .radius(5000)
        .types(PlaceAutocompleteType.ESTABLISHMENT)
        .components(ComponentFilter.country("AU"))
        .await();

    sc.assertParamValue("Sydney Town Hall", "input");
    sc.assertParamValue(Integer.toString(4), "offset");
    sc.assertParamValue(location.toUrlValue(), "origin");
    sc.assertParamValue(location.toUrlValue(), "location");
    sc.assertParamValue("5000", "radius");
    sc.assertParamValue(PlaceAutocompleteType.ESTABLISHMENT.toString(), "types");
    sc.assertParamValue(ComponentFilter.country("AU").toString(), "components");
    sc.assertParamValue(session.toUrlValue(), "sessiontoken");
  }
}
 
Example #8
Source File: RoadsApiIntegrationTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testNearestRoads() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext(nearestRoadsResponse)) {
    LatLng[] path =
        new LatLng[] {
          new LatLng(-33.865382, 151.192861),
          new LatLng(-33.865837, 151.193376),
          new LatLng(-33.866745, 151.19373),
          new LatLng(-33.867128, 151.19344),
          new LatLng(-33.867547, 151.193676),
          new LatLng(-33.867841, 151.194137),
          new LatLng(-33.868224, 151.194116)
        };
    SnappedPoint[] points = RoadsApi.nearestRoads(sc.context, path).await();

    assertNotNull(Arrays.toString(points));
    assertEquals("/v1/nearestRoads", sc.path());
    sc.assertParamValue(join('|', path), "points");
    assertEquals(13, points.length);
    assertEquals(-33.86543615612047, points[0].location.lat, 0.0001);
    assertEquals(151.1930101572747, points[0].location.lng, 0.0001);
    assertEquals("ChIJ0XXACjauEmsRUduC5Wd9ARM", points[0].placeId);
  }
}
 
Example #9
Source File: GeocodingApiTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
/**
 * Simple reverse geocoding. <a
 * href="https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452">Reverse
 * geocode (40.714224,-73.961452)</a>.
 */
@Test
public void testSimpleReverseGeocode() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext(simpleReverseGeocodeResponse)) {
    LatLng latlng = new LatLng(40.714224, -73.961452);
    GeocodingResult[] results = GeocodingApi.newRequest(sc.context).latlng(latlng).await();

    assertNotNull(results);
    assertNotNull(Arrays.toString(results));
    assertEquals("277 Bedford Ave, Brooklyn, NY 11211, USA", results[0].formattedAddress);
    assertEquals("277", results[0].addressComponents[0].longName);
    assertEquals("277", results[0].addressComponents[0].shortName);
    assertEquals(AddressComponentType.STREET_NUMBER, results[0].addressComponents[0].types[0]);
    assertEquals(AddressType.STREET_ADDRESS, results[0].types[0]);

    sc.assertParamValue(latlng.toUrlValue(), "latlng");
  }
}
 
Example #10
Source File: RoadsApiIntegrationTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSnappedSpeedLimitRequest() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext(snappedSpeedLimitResponse)) {
    LatLng[] path =
        new LatLng[] {
          new LatLng(-33.865382, 151.192861),
          new LatLng(-33.865837, 151.193376),
          new LatLng(-33.866745, 151.19373),
          new LatLng(-33.867128, 151.19344),
          new LatLng(-33.867547, 151.193676),
          new LatLng(-33.867841, 151.194137),
          new LatLng(-33.868224, 151.194116)
        };
    SnappedSpeedLimitResponse response = RoadsApi.snappedSpeedLimits(sc.context, path).await();

    assertNotNull(response.toString());
    assertEquals("/v1/speedLimits", sc.path());
    sc.assertParamValue(join('|', path), "path");
    assertEquals(path.length, response.snappedPoints.length);
    assertEquals(path.length, response.speedLimits.length);
  }
}
 
Example #11
Source File: MainActivity.java    From roads-api-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the GPX button-click event, running the demo snippet {@link #loadGpxData}.
 */
public void onGpxButtonClick(View view) {
    try {
        mCapturedLocations = loadGpxData(Xml.newPullParser(),
                getResources().openRawResource(R.raw.gpx_data));
        findViewById(R.id.snap_to_roads).setEnabled(true);

        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        PolylineOptions polyline = new PolylineOptions();

        for (LatLng ll : mCapturedLocations) {
            com.google.android.gms.maps.model.LatLng mapPoint =
                    new com.google.android.gms.maps.model.LatLng(ll.lat, ll.lng);
            builder.include(mapPoint);
            polyline.add(mapPoint);
        }

        mMap.addPolyline(polyline.color(Color.RED));
        mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 0));
    } catch (XmlPullParserException | IOException e) {
        e.printStackTrace();
        toastException(e);
    }
}
 
Example #12
Source File: MainActivity.java    From roads-api-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the waypoint (wpt tags) data into native objects from a GPX stream.
 */
private List<LatLng> loadGpxData(XmlPullParser parser, InputStream gpxIn)
        throws XmlPullParserException, IOException {
    List<LatLng> latLngs = new ArrayList<>();   // List<> as we need subList for paging later
    parser.setInput(gpxIn, null);
    parser.nextTag();

    while (parser.next() != XmlPullParser.END_DOCUMENT) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }

        if (parser.getName().equals("wpt")) {
            // Save the discovered lat/lon attributes in each <wpt>
            latLngs.add(new LatLng(
                    Double.valueOf(parser.getAttributeValue(null, "lat")),
                    Double.valueOf(parser.getAttributeValue(null, "lon"))));
        }
        // Otherwise, skip irrelevant data
    }

    return latLngs;
}
 
Example #13
Source File: RoadsApiIntegrationTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpeedLimitsWithUsaLatLngs() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext(speedLimitsUSAResponse)) {
    LatLng[] path =
        new LatLng[] {
          new LatLng(33.777489, -84.397805),
          new LatLng(33.777550, -84.395700),
          new LatLng(33.776900, -84.393110),
          new LatLng(33.776860, -84.389550),
          new LatLng(33.775491, -84.388797),
          new LatLng(33.773250, -84.388840),
          new LatLng(33.771991, -84.388840)
        };
    SpeedLimit[] speeds = RoadsApi.speedLimits(sc.context, path).await();

    assertNotNull(Arrays.toString(speeds));
    assertEquals("/v1/speedLimits", sc.path());
    sc.assertParamValue(join('|', path), "path");
    assertEquals(7, speeds.length);

    for (SpeedLimit speed : speeds) {
      assertNotNull(speed.placeId);
      assertTrue(speed.speedLimit > 0);
    }
  }
}
 
Example #14
Source File: RoadsApiIntegrationTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSnapToRoad() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext(snapToRoadResponse)) {
    LatLng[] path =
        new LatLng[] {
          new LatLng(-33.865382, 151.192861),
          new LatLng(-33.865837, 151.193376),
          new LatLng(-33.866745, 151.19373),
          new LatLng(-33.867128, 151.19344),
          new LatLng(-33.867547, 151.193676),
          new LatLng(-33.867841, 151.194137),
          new LatLng(-33.868224, 151.194116)
        };
    SnappedPoint[] points = RoadsApi.snapToRoads(sc.context, false, path).await();

    assertNotNull(Arrays.toString(points));
    sc.assertParamValue(join('|', path), "path");
    sc.assertParamValue("false", "interpolate");
    assertEquals(7, points.length);
    assertEquals(-33.86523340256843, points[0].location.lat, 0.0001);
    assertEquals(151.19288612197704, points[0].location.lng, 0.0001);
    assertEquals("ChIJjXkMCDauEmsRp5xab4Ske6k", points[0].placeId);
  }
}
 
Example #15
Source File: TimezoneWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    String latlong = (String) workItem.getParameter("LatLong");

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String[] latlongParts = latlong.split(",");
        Map<String, Object> results = new HashMap<>();

        TimeZone timeZone = TimeZoneApi.getTimeZone(geoApiContext,
                                                    new LatLng(Double.parseDouble(latlongParts[0]),
                                                               Double.parseDouble(latlongParts[1]))).await();
        results.put(RESULTS_VALUE,
                    timeZone);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example #16
Source File: ArmeriaRequestHandler.java    From curiostack with MIT License 6 votes vote down vote up
private static Gson gsonForPolicy(FieldNamingPolicy fieldNamingPolicy) {
  return GSONS.computeIfAbsent(
      fieldNamingPolicy,
      policy ->
          new GsonBuilder()
              .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeAdapter())
              .registerTypeAdapter(Distance.class, new DistanceAdapter())
              .registerTypeAdapter(Duration.class, new DurationAdapter())
              .registerTypeAdapter(Fare.class, new FareAdapter())
              .registerTypeAdapter(LatLng.class, new LatLngAdapter())
              .registerTypeAdapter(
                  AddressComponentType.class, new SafeEnumAdapter<>(AddressComponentType.UNKNOWN))
              .registerTypeAdapter(AddressType.class, new SafeEnumAdapter<>(AddressType.UNKNOWN))
              .registerTypeAdapter(TravelMode.class, new SafeEnumAdapter<>(TravelMode.UNKNOWN))
              .registerTypeAdapter(
                  LocationType.class, new SafeEnumAdapter<>(LocationType.UNKNOWN))
              .registerTypeAdapter(RatingType.class, new SafeEnumAdapter<>(RatingType.UNKNOWN))
              .registerTypeAdapter(DayOfWeek.class, new DayOfWeekAdapter())
              .registerTypeAdapter(PriceLevel.class, new PriceLevelAdapter())
              .registerTypeAdapter(Instant.class, new InstantAdapter())
              .registerTypeAdapter(LocalTime.class, new LocalTimeAdapter())
              .registerTypeAdapter(
                  GeolocationApi.Response.class, new GeolocationResponseAdapter())
              .setFieldNamingPolicy(policy)
              .create());
}
 
Example #17
Source File: ElevationApiTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDirectionsAlongPath() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext(directionsAlongPath)) {
    ElevationResult[] elevation = ElevationApi.getByPath(sc.context, 100, SYD_MELB_ROUTE).await();
    assertEquals(100, elevation.length);

    List<LatLng> overviewPolylinePath = SYD_MELB_ROUTE.decodePath();
    LatLng lastDirectionsPoint = overviewPolylinePath.get(overviewPolylinePath.size() - 1);
    LatLng lastElevationPoint = elevation[elevation.length - 1].location;

    LatLngAssert.assertEquals(lastDirectionsPoint, lastElevationPoint, EPSILON);

    sc.assertParamValue("100", "samples");
    sc.assertParamValue("enc:" + SYD_MELB_ROUTE.getEncodedPath(), "path");
  }
}
 
Example #18
Source File: ElevationApiTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = RequestDeniedException.class)
public void testGetByPointsThrowsRequestDeniedExceptionFromResponse() throws Exception {
  try (LocalTestServerContext sc =
      new LocalTestServerContext(
          ""
              + "{\n"
              + "   \"routes\" : [],\n"
              + "   \"status\" : \"REQUEST_DENIED\",\n"
              + "   \"errorMessage\" : \"Can't do the thing\"\n"
              + "}")) {

    // This should throw the RequestDeniedException
    ElevationApi.getByPoints(
            sc.context, new EncodedPolyline(Collections.singletonList(new LatLng(0, 0))))
        .await();
  }
}
 
Example #19
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 #20
Source File: DirectionsApiTest.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
/**
 * Boston to Concord, via Charlestown and Lexington, but using exact latitude and longitude
 * coordinates for the waypoints, using non-stopover waypoints.
 *
 * <p>{@code
 * http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&waypoints=via:42.379322,-71.063384|via:42.444303,-71.229087}
 */
@Test
public void testBostonToConcordViaCharlestownAndLexingtonLatLngNonStopoever() throws Exception {
  try (LocalTestServerContext sc =
      new LocalTestServerContext("{\"routes\": [{}],\"status\": \"OK\"}")) {
    DirectionsApi.newRequest(sc.context)
        .origin("Boston,MA")
        .destination("Concord,MA")
        .waypoints(
            new DirectionsApiRequest.Waypoint(new LatLng(42.379322, -71.063384), false),
            new DirectionsApiRequest.Waypoint(new LatLng(42.444303, -71.229087), false))
        .await();

    sc.assertParamValue("Boston,MA", "origin");
    sc.assertParamValue("Concord,MA", "destination");
    sc.assertParamValue("via:42.37932200,-71.06338400|via:42.44430300,-71.22908700", "waypoints");
  }
}
 
Example #21
Source File: MainActivity.java    From roads-api-samples with Apache License 2.0 6 votes vote down vote up
@Override
protected void onPostExecute(List<SnappedPoint> snappedPoints) {
    mSnappedPoints = snappedPoints;
    mProgressBar.setVisibility(View.INVISIBLE);

    findViewById(R.id.speed_limits).setEnabled(true);

    com.google.android.gms.maps.model.LatLng[] mapPoints =
            new com.google.android.gms.maps.model.LatLng[mSnappedPoints.size()];
    int i = 0;
    LatLngBounds.Builder bounds = new LatLngBounds.Builder();
    for (SnappedPoint point : mSnappedPoints) {
        mapPoints[i] = new com.google.android.gms.maps.model.LatLng(point.location.lat,
                point.location.lng);
        bounds.include(mapPoints[i]);
        i += 1;
    }

    mMap.addPolyline(new PolylineOptions().add(mapPoints).color(Color.BLUE));
    mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 0));
}
 
Example #22
Source File: PolylineEncodingTest.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecode() throws Exception {
  List<LatLng> points = PolylineEncoding.decode(SYD_MELB_ROUTE);
  LatLng sydney = points.get(0);
  LatLng melbourne = points.get(points.size() - 1);

  assertEquals(SYDNEY, sydney, EPSILON);
  assertEquals(MELBOURNE, melbourne, EPSILON);
}
 
Example #23
Source File: PlacesApiTest.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testTextSearchRequest() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext("{\"status\" : \"OK\"}")) {
    LatLng location = new LatLng(10, 20);
    PlacesApi.textSearchQuery(sc.context, "Google Sydney")
        .location(location)
        .region("AU")
        .radius(3000)
        .minPrice(PriceLevel.INEXPENSIVE)
        .maxPrice(PriceLevel.VERY_EXPENSIVE)
        .name("name")
        .openNow(true)
        .rankby(RankBy.DISTANCE)
        .type(PlaceType.AIRPORT)
        .await();

    sc.assertParamValue("Google Sydney", "query");
    sc.assertParamValue(location.toUrlValue(), "location");
    sc.assertParamValue("AU", "region");
    sc.assertParamValue(String.valueOf(3000), "radius");
    sc.assertParamValue(String.valueOf(1), "minprice");
    sc.assertParamValue(String.valueOf(4), "maxprice");
    sc.assertParamValue("name", "name");
    sc.assertParamValue("true", "opennow");
    sc.assertParamValue(RankBy.DISTANCE.toString(), "rankby");
    sc.assertParamValue(PlaceType.AIRPORT.toString(), "type");
  }
}
 
Example #24
Source File: PlacesApiTest.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testTextSearchRequestWithLocation() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext("{\"status\" : \"OK\"}")) {
    LatLng location = new LatLng(10, 20);
    PlacesApi.textSearchQuery(sc.context, "Google Sydney", location)
        .region("AU")
        .radius(3000)
        .minPrice(PriceLevel.INEXPENSIVE)
        .maxPrice(PriceLevel.VERY_EXPENSIVE)
        .name("name")
        .openNow(true)
        .rankby(RankBy.DISTANCE)
        .type(PlaceType.AIRPORT)
        .await();

    sc.assertParamValue("Google Sydney", "query");
    sc.assertParamValue(location.toUrlValue(), "location");
    sc.assertParamValue("AU", "region");
    sc.assertParamValue(String.valueOf(3000), "radius");
    sc.assertParamValue(String.valueOf(1), "minprice");
    sc.assertParamValue(String.valueOf(4), "maxprice");
    sc.assertParamValue("name", "name");
    sc.assertParamValue("true", "opennow");
    sc.assertParamValue(RankBy.DISTANCE.toString(), "rankby");
    sc.assertParamValue(PlaceType.AIRPORT.toString(), "type");
  }
}
 
Example #25
Source File: PlacesApiTest.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testTextSearchRequestWithType() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext("{\"status\" : \"OK\"}")) {
    LatLng location = new LatLng(-33.866611, 151.195832);
    PlacesSearchResponse results =
        PlacesApi.textSearchQuery(sc.context, PlaceType.ZOO)
            .location(location)
            .radius(500)
            .await();

    sc.assertParamValue(location.toUrlValue(), "location");
    sc.assertParamValue(String.valueOf(500), "radius");
    sc.assertParamValue(PlaceType.ZOO.toString(), "type");
  }
}
 
Example #26
Source File: PlacesApiTest.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testTextSearchLocationWithoutRadius() throws Exception {
  try (LocalTestServerContext sc = new LocalTestServerContext("{\"status\" : \"OK\"}")) {
    LatLng location = new LatLng(10, 20);
    PlacesApi.textSearchQuery(sc.context, "query").location(location).await();
  }
}
 
Example #27
Source File: ElevationApi.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
/**
 * See <a href="https://developers.google.com/maps/documentation/elevation/intro#Paths">
 * documentation</a>.
 *
 * @param context The {@link GeoApiContext} to make requests through.
 * @param samples The number of samples to retrieve heights along {@code path}.
 * @param path The path to sample.
 * @return The elevations as a {@link PendingResult}.
 */
public static PendingResult<ElevationResult[]> getByPath(
    GeoApiContext context, int samples, LatLng... path) {
  return context.get(
      API_CONFIG,
      MultiResponse.class,
      "samples",
      String.valueOf(samples),
      "path",
      shortestParam(path));
}
 
Example #28
Source File: ElevationApiTest.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = InvalidRequestException.class)
public void testGetByPointThrowsInvalidRequestExceptionFromResponse() throws Exception {
  try (LocalTestServerContext sc =
      new LocalTestServerContext(
          "{\n   \"routes\" : [],\n   \"status\" : \"INVALID_REQUEST\"\n}")) {

    // This should throw the InvalidRequestException
    ElevationApi.getByPoint(sc.context, new LatLng(0, 0)).await();
  }
}
 
Example #29
Source File: TimeZoneApi.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the {@link java.util.TimeZone} for the given location.
 *
 * @param context The {@link GeoApiContext} to make requests through.
 * @param location The location for which to retrieve a time zone.
 * @return Returns the time zone as a {@link PendingResult}.
 */
public static PendingResult<TimeZone> getTimeZone(GeoApiContext context, LatLng location) {
  return context.get(
      API_CONFIG,
      Response.class,
      "location",
      location.toString(),
      // Java has its own lookup for time -> DST, so we really only need to fetch the TZ id.
      // "timestamp" is, in effect, ignored.
      "timestamp",
      "0");
}
 
Example #30
Source File: PolylineEncoding.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
/** Decodes an encoded path string into a sequence of LatLngs. */
public static List<LatLng> decode(final String encodedPath) {

  int len = encodedPath.length();

  final List<LatLng> path = new ArrayList<>(len / 2);
  int index = 0;
  int lat = 0;
  int lng = 0;

  while (index < len) {
    int result = 1;
    int shift = 0;
    int b;
    do {
      b = encodedPath.charAt(index++) - 63 - 1;
      result += b << shift;
      shift += 5;
    } while (b >= 0x1f);
    lat += (result & 1) != 0 ? ~(result >> 1) : (result >> 1);

    result = 1;
    shift = 0;
    do {
      b = encodedPath.charAt(index++) - 63 - 1;
      result += b << shift;
      shift += 5;
    } while (b >= 0x1f);
    lng += (result & 1) != 0 ? ~(result >> 1) : (result >> 1);

    path.add(new LatLng(lat * 1e-5, lng * 1e-5));
  }

  return path;
}