com.google.android.gms.maps.model.LatLng

Here are the examples of the java api class com.google.android.gms.maps.model.LatLng taken from open source projects.

1. MapFragment#drawPolygon()

View license
private void drawPolygon(LatLng startingLocation) {
    LatLng point2 = new LatLng(startingLocation.latitude + .001, startingLocation.longitude);
    LatLng point3 = new LatLng(startingLocation.latitude, startingLocation.longitude + .001);
    PolygonOptions options = new PolygonOptions();
    options.add(startingLocation, point2, point3);
    options.fillColor(getResources().getColor(R.color.fill_color));
    options.strokeColor(getResources().getColor(R.color.stroke_color));
    options.strokeWidth(10);
    getMap().addPolygon(options);
}

2. SphericalUtil#computeSignedArea()

View license
/**
     * Returns the signed area of a closed path on a sphere of given radius.
     * The computed area uses the same units as the radius squared.
     * Used by SphericalUtilTest.
     */
static double computeSignedArea(List<LatLng> path, double radius) {
    int size = path.size();
    if (size < 3) {
        return 0;
    }
    double total = 0;
    LatLng prev = path.get(size - 1);
    double prevTanLat = tan((PI / 2 - toRadians(prev.latitude)) / 2);
    double prevLng = toRadians(prev.longitude);
    // and that edge ("polar triangle").
    for (LatLng point : path) {
        double tanLat = tan((PI / 2 - toRadians(point.latitude)) / 2);
        double lng = toRadians(point.longitude);
        total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
        prevTanLat = tanLat;
        prevLng = lng;
    }
    return total * (radius * radius);
}

3. SphericalUtil#computeLength()

View license
/**
     * Returns the length of the given path, in meters, on Earth.
     */
public static double computeLength(List<LatLng> path) {
    if (path.size() < 2) {
        return 0;
    }
    double length = 0;
    LatLng prev = path.get(0);
    double prevLat = toRadians(prev.latitude);
    double prevLng = toRadians(prev.longitude);
    for (LatLng point : path) {
        double lat = toRadians(point.latitude);
        double lng = toRadians(point.longitude);
        length += distanceRadians(prevLat, prevLng, lat, lng);
        prevLat = lat;
        prevLng = lng;
    }
    return length * EARTH_RADIUS;
}

4. SphericalUtil#computeSignedArea()

View license
/**
     * Returns the signed area of a closed path on a sphere of given radius.
     * The computed area uses the same units as the radius squared.
     * Used by SphericalUtilTest.
     */
static double computeSignedArea(List<LatLng> path, double radius) {
    int size = path.size();
    if (size < 3) {
        return 0;
    }
    double total = 0;
    LatLng prev = path.get(size - 1);
    double prevTanLat = tan((PI / 2 - toRadians(prev.latitude)) / 2);
    double prevLng = toRadians(prev.longitude);
    // and that edge ("polar triangle").
    for (LatLng point : path) {
        double tanLat = tan((PI / 2 - toRadians(point.latitude)) / 2);
        double lng = toRadians(point.longitude);
        total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
        prevTanLat = tanLat;
        prevLng = lng;
    }
    return total * (radius * radius);
}

5. SphericalUtil#computeLength()

View license
/**
     * Returns the length of the given path, in meters, on Earth.
     */
public static double computeLength(List<LatLng> path) {
    if (path.size() < 2) {
        return 0;
    }
    double length = 0;
    LatLng prev = path.get(0);
    double prevLat = toRadians(prev.latitude);
    double prevLng = toRadians(prev.longitude);
    for (LatLng point : path) {
        double lat = toRadians(point.latitude);
        double lng = toRadians(point.longitude);
        length += distanceRadians(prevLat, prevLng, lat, lng);
        prevLat = lat;
        prevLng = lng;
    }
    return length * EARTH_RADIUS;
}

6. PolyUtil#encode()

Project: android-maps-utils
Source File: PolyUtil.java
View license
/**
     * 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 StringBuffer result = new StringBuffer();
    for (final LatLng point : path) {
        long lat = Math.round(point.latitude * 1e5);
        long lng = Math.round(point.longitude * 1e5);
        long dLat = lat - lastLat;
        long dLng = lng - lastLng;
        encode(dLat, result);
        encode(dLng, result);
        lastLat = lat;
        lastLng = lng;
    }
    return result.toString();
}

7. CircleDemoActivity#onMapLongClick()

View license
@Override
public void onMapLongClick(LatLng point) {
    // We know the center, let's place the outline at a point 3/4 along the view.
    View view = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getView();
    LatLng radiusLatLng = mMap.getProjection().fromScreenLocation(new Point(view.getHeight() * 3 / 4, view.getWidth() * 3 / 4));
    // ok create it
    DraggableCircle circle = new DraggableCircle(point, radiusLatLng, mClickabilityCheckbox.isChecked());
    mCircles.add(circle);
}

8. PlacesSampleActivity#showPlace()

View license
/**
   * Show a place in PlaceFragment and SupportMapFragment and apply the maximize effect over the
   * DraggablePanel.
   */
private void showPlace(int position) {
    draggablePanel.setVisibility(View.VISIBLE);
    draggablePanel.maximize();
    PlaceViewModel placeViewModel = placesAdapter.getItem(position);
    placeFragment.showPlace(placeViewModel);
    mapFragment.getMap().clear();
    LatLng latitudeLongitude = new LatLng(placeViewModel.getLatitude(), placeViewModel.getLongitude());
    MarkerOptions marker = new MarkerOptions().position(latitudeLongitude);
    marker.title(placeViewModel.getName());
    marker.snippet(placeViewModel.getLatitude() + " , " + placeViewModel.getLongitude());
    mapFragment.getMap().addMarker(marker);
    mapFragment.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(latitudeLongitude, ZOOM));
}

9. AbstractDetailActivity#setupMap()

View license
private void setupMap() {
    final GoogleMap map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    double lat = getIntent().getDoubleExtra("lat", 37.6329946);
    double lng = getIntent().getDoubleExtra("lng", -122.4938344);
    float zoom = getIntent().getFloatExtra("zoom", 15);
    LatLng position = new LatLng(lat, lng);
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, zoom));
    map.addMarker(new MarkerOptions().position(position));
    // We need the snapshot of the map to prepare the shader for the circular reveal.
    // So the map is visible on activity start and then once the snapshot is taken, quickly hidden.
    map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {

        @Override
        public void onMapLoaded() {
            map.snapshot(new GoogleMap.SnapshotReadyCallback() {

                @Override
                public void onSnapshotReady(Bitmap bitmap) {
                    mapLoaded(bitmap);
                }
            });
        }
    });
}

10. NearByPatientsActivity#drawMarker()

View license
public void drawMarker(Patient patient) {
    AppLog.enter(TAG, AppLog.getMethodName());
    double patientLat = Double.parseDouble(patient.getLatitude());
    double patientLong = Double.parseDouble(patient.getLongitude());
    LatLng position = new LatLng(patientLat, patientLong);
    if (null != mGoogleMap) {
        mGoogleMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_patient_icon)));
    }
    AppLog.exit(TAG, AppLog.getMethodName());
}

11. NearByVehicleActivity#drawMarker()

View license
public void drawMarker(Vehicle vehicle) {
    AppLog.enter(TAG, AppLog.getMethodName());
    double vehicleLat = Double.parseDouble(vehicle.getLatitude());
    double vehicleLong = Double.parseDouble(vehicle.getLongitude());
    LatLng position = new LatLng(vehicleLat, vehicleLong);
    MarkerOptions vehicleMarker = new MarkerOptions();
    vehicleMarker.position(position);
    if (null != mGoogleMap) {
        mGoogleMap.addMarker(vehicleMarker).setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_car_icon));
    }
    AppLog.exit(TAG, AppLog.getMethodName());
}

12. MapActivity#onLocationChanged()

View license
@Override
public void onLocationChanged(Location location) {
    lastLocation = location;
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    LatLng latLng = new LatLng(latitude, longitude);
    if (myMarker == null) {
        myMarker = googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_my)));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    } else {
        myMarker.setPosition(latLng);
    }
}

13. ExploreFragment#onMapReady()

Project: rox-android
Source File: ExploreFragment.java
View license
@Override
public void onMapReady(GoogleMap googleMap) {
    this.googleMap = googleMap;
    googleMap.getUiSettings().setMapToolbarEnabled(false);
    googleMap.getUiSettings().setMyLocationButtonEnabled(false);
    LatLng latLng = new LatLng(PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat(getString(R.string.last_map_location_lat_key), 0f), PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat(getString(R.string.last_map_location_lng_key), 0f));
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat(getString(R.string.last_map_zoom_key), 0f)));
    googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(Marker marker) {
            int position = currentMarkers.indexOf(marker);
            viewPager.setCurrentItem(position, true);
            return false;
        }
    });
    if (shouldRestoreCurrentLocationInMap)
        showCurrentLocationInMap();
    if (shouldRestoreRecommendationsInMap)
        restoreRecommendationsInMap();
    if (shouldRestorePois)
        restorePoisInMap();
}

14. ExploreFragment#onLocationChanged()

Project: rox-android
Source File: ExploreFragment.java
View license
@Override
public void onLocationChanged(Location location) {
    shouldRequestLocationUpdatesOnConnect = false;
    shouldRestoreCurrentLocationInMap = true;
    currentLocation = location;
    stopLocationUpdates();
    onCompleteLocationUpdate();
    googleMap.clear();
    showCurrentLocationInMap();
    LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
    float zoom = googleMap.getCameraPosition().zoom;
    if (zoom < 12.5f)
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.5f));
    else
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    recommendationsTask = new RecommendationsTask().location(location).radius(getRadiusFromMapProjection());
    recommendationsTask.request();
}

15. GoogleMapFragment#addFlightPathPoint()

Project: Tower
Source File: GoogleMapFragment.java
View license
@Override
public void addFlightPathPoint(LatLong coord) {
    final LatLng position = DroneHelper.CoordToLatLang(coord);
    if (maxFlightPathSize > 0) {
        if (flightPath == null) {
            PolylineOptions flightPathOptions = new PolylineOptions();
            flightPathOptions.color(FLIGHT_PATH_DEFAULT_COLOR).width(FLIGHT_PATH_DEFAULT_WIDTH).zIndex(1);
            flightPath = getMap().addPolyline(flightPathOptions);
        }
        List<LatLng> oldFlightPath = flightPath.getPoints();
        if (oldFlightPath.size() > maxFlightPathSize) {
            oldFlightPath.remove(0);
        }
        oldFlightPath.add(position);
        flightPath.setPoints(oldFlightPath);
    }
}

16. GoogleMapFragment#updateMarker()

Project: Tower
Source File: GoogleMapFragment.java
View license
@Override
public void updateMarker(MarkerInfo markerInfo, boolean isDraggable) {
    // if the drone hasn't received a gps signal yet
    final LatLong coord = markerInfo.getPosition();
    if (coord == null) {
        return;
    }
    final LatLng position = DroneHelper.CoordToLatLang(coord);
    Marker marker = mBiMarkersMap.getValue(markerInfo);
    if (marker == null) {
        // Generate the marker
        generateMarker(markerInfo, position, isDraggable);
    } else {
        // Update the marker
        updateMarker(marker, markerInfo, position, isDraggable);
    }
}

17. KmlFeatureParser#createPoint()

View license
/**
     * Creates a new KmlPoint object
     *
     * @return KmlPoint object
     */
private static KmlPoint createPoint(XmlPullParser parser) throws XmlPullParserException, IOException {
    LatLng coordinate = null;
    int eventType = parser.getEventType();
    while (!(eventType == END_TAG && parser.getName().equals("Point"))) {
        if (eventType == START_TAG && parser.getName().equals("coordinates")) {
            coordinate = convertToLatLng(parser.nextText());
        }
        eventType = parser.next();
    }
    return new KmlPoint(coordinate);
}

18. PolyUtil#encode()

Project: wigle-wifi-wardriving
Source File: PolyUtil.java
View license
/**
     * 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 StringBuffer result = new StringBuffer();
    for (final LatLng point : path) {
        long lat = Math.round(point.latitude * 1e5);
        long lng = Math.round(point.longitude * 1e5);
        long dLat = lat - lastLat;
        long dLng = lng - lastLng;
        encode(dLat, result);
        encode(dLng, result);
        lastLat = lat;
        lastLng = lng;
    }
    return result.toString();
}

19. KmlFeatureParser#createPoint()

View license
/**
     * Creates a new KmlPoint object
     *
     * @return KmlPoint object
     */
private static KmlPoint createPoint(XmlPullParser parser) throws XmlPullParserException, IOException {
    LatLng coordinate = null;
    int eventType = parser.getEventType();
    while (!(eventType == END_TAG && parser.getName().equals("Point"))) {
        if (eventType == START_TAG && parser.getName().equals("coordinates")) {
            coordinate = convertToLatLng(parser.nextText());
        }
        eventType = parser.next();
    }
    return new KmlPoint(coordinate);
}

20. KmlDemoActivity#moveCameraToKml()

View license
private void moveCameraToKml(KmlLayer kmlLayer) {
    //Retrieve the first container in the KML layer
    KmlContainer container = kmlLayer.getContainers().iterator().next();
    //Retrieve a nested container within the first container
    container = container.getContainers().iterator().next();
    //Retrieve the first placemark in the nested container
    KmlPlacemark placemark = container.getPlacemarks().iterator().next();
    //Retrieve a polygon object in a placemark
    KmlPolygon polygon = (KmlPolygon) placemark.getGeometry();
    //Create LatLngBounds of the outer coordinates of the polygon
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (LatLng latLng : polygon.getOuterBoundaryCoordinates()) {
        builder.include(latLng);
    }
    getMap().moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 1));
}

21. MappingFragment#onCreateView()

View license
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mapView = new MapView(getActivity());
    final int serviceAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
    if (serviceAvailable == ConnectionResult.SUCCESS) {
        mapView.onCreate(savedInstanceState);
    } else {
        Toast.makeText(getActivity(), getString(R.string.map_needs_playservice), Toast.LENGTH_LONG).show();
    }
    MapsInitializer.initialize(getActivity());
    final View view = inflater.inflate(R.layout.map, container, false);
    LatLng oldCenter = null;
    int oldZoom = Integer.MIN_VALUE;
    if (state.oldCenter != null) {
        // pry an orientation change, which calls destroy
        oldCenter = state.oldCenter;
        oldZoom = state.oldZoom;
    }
    setupMapView(view, oldCenter, oldZoom);
    return view;
}

22. MainActivity#onMapInitialized()

Project: AirMapView
Source File: MainActivity.java
View license
@Override
public void onMapInitialized() {
    appendLog("Map onMapInitialized triggered");
    final LatLng airbnbLatLng = new LatLng(37.771883, -122.405224);
    addMarker("Airbnb HQ", airbnbLatLng, 1);
    addMarker("Performance Bikes", new LatLng(37.773975, -122.40205), 2);
    addMarker("REI", new LatLng(37.772127, -122.404411), 3);
    addMarker("Mapbox", new LatLng(37.77572, -122.41354), 4);
    map.animateCenterZoom(airbnbLatLng, 10);
    // Add Polylines
    LatLng[] latLngs = { new LatLng(37.77977, -122.38937), new LatLng(37.77811, -122.39160), new LatLng(37.77787, -122.38864) };
    map.addPolyline(new AirMapPolyline(Arrays.asList(latLngs), 5));
    // Add Polygons
    LatLng[] polygonLatLngs = { new LatLng(37.784, -122.405), new LatLng(37.784, -122.406), new LatLng(37.785, -122.406), new LatLng(37.785, -122.405) };
    map.addPolygon(new AirMapPolygon.Builder().add(polygonLatLngs).strokeWidth(3.f).build());
    // Add Circle
    map.drawCircle(new LatLng(37.78443, -122.40805), 1000);
    // enable my location
    map.setMyLocationEnabled(true);
}

23. PolyUtil#isClosedPolygon()

Project: wigle-wifi-wardriving
Source File: PolyUtil.java
View license
/**
     * Returns true if the provided list of points is a closed polygon (i.e., the first and last
     * points are the same), and false if it is not
     * @param poly polyline or polygon
     * @return true if the provided list of points is a closed polygon (i.e., the first and last
     * points are the same), and false if it is not
     */
public static boolean isClosedPolygon(List<LatLng> poly) {
    LatLng firstPoint = poly.get(0);
    LatLng lastPoint = poly.get(poly.size() - 1);
    if (firstPoint.equals(lastPoint)) {
        return true;
    } else {
        return false;
    }
}

24. PolyUtilTest#testSimplify()

View license
public void testSimplify() {
    /**
         * Polyline
         */
    final String LINE = "elfjD~a}[email protected]@[email protected]^[email protected][email protected]`[email protected]{@DwCA{CF_EC{[email protected][email protected][email protected][email protected][email protected][email protected][email protected]@`@@[email protected][email protected][email protected][email protected]?vAH`@[email protected]^ETFJCLD?JA^?J?P?fAC`[email protected]@[email protected]\\@`@[email protected]@\\?`@[email protected][email protected][email protected]@@@[email protected]@[email protected][email protected]@[email protected]@@[email protected]@";
    List<LatLng> line = PolyUtil.decode(LINE);
    assertEquals(95, line.size());
    List<LatLng> simplifiedLine;
    List<LatLng> copy;
    // meters
    double tolerance = 5;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(21, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 10;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(14, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 15;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(10, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 20;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(8, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 50;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(6, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 500;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(3, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 1000;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(2, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    /**
         * Polygons
         */
    // Open triangle
    ArrayList<LatLng> triangle = new ArrayList<>();
    triangle.add(new LatLng(28.06025, -82.41030));
    triangle.add(new LatLng(28.06129, -82.40945));
    triangle.add(new LatLng(28.06206, -82.40917));
    triangle.add(new LatLng(28.06125, -82.40850));
    triangle.add(new LatLng(28.06035, -82.40834));
    triangle.add(new LatLng(28.06038, -82.40924));
    assertFalse(PolyUtil.isClosedPolygon(triangle));
    copy = copyList(triangle);
    // meters
    tolerance = 88;
    List simplifiedTriangle = PolyUtil.simplify(triangle, tolerance);
    assertEquals(4, simplifiedTriangle.size());
    assertEndPoints(triangle, simplifiedTriangle);
    assertSimplifiedPointsFromLine(triangle, simplifiedTriangle);
    assertLineLength(triangle, simplifiedTriangle);
    assertInputUnchanged(triangle, copy);
    // Close the triangle
    LatLng p = triangle.get(0);
    LatLng closePoint = new LatLng(p.latitude, p.longitude);
    triangle.add(closePoint);
    assertTrue(PolyUtil.isClosedPolygon(triangle));
    copy = copyList(triangle);
    // meters
    tolerance = 88;
    simplifiedTriangle = PolyUtil.simplify(triangle, tolerance);
    assertEquals(4, simplifiedTriangle.size());
    assertEndPoints(triangle, simplifiedTriangle);
    assertSimplifiedPointsFromLine(triangle, simplifiedTriangle);
    assertLineLength(triangle, simplifiedTriangle);
    assertInputUnchanged(triangle, copy);
    // Open oval
    final String OVAL_POLYGON = "}[email protected]}AN{A][email protected][email protected]?{@[email protected]@[email protected]]D[FULWFOLSNMTOVOXO\\I\\CX?VJXJTDTNXTVVLVJ`@FXA\\[email protected]?\\[email protected]";
    List<LatLng> oval = PolyUtil.decode(OVAL_POLYGON);
    assertFalse(PolyUtil.isClosedPolygon(oval));
    copy = copyList(oval);
    // meters
    tolerance = 10;
    List simplifiedOval = PolyUtil.simplify(oval, tolerance);
    assertEquals(13, simplifiedOval.size());
    assertEndPoints(oval, simplifiedOval);
    assertSimplifiedPointsFromLine(oval, simplifiedOval);
    assertLineLength(oval, simplifiedOval);
    assertInputUnchanged(oval, copy);
    // Close the oval
    p = oval.get(0);
    closePoint = new LatLng(p.latitude, p.longitude);
    oval.add(closePoint);
    assertTrue(PolyUtil.isClosedPolygon(oval));
    copy = copyList(oval);
    // meters
    tolerance = 10;
    simplifiedOval = PolyUtil.simplify(oval, tolerance);
    assertEquals(13, simplifiedOval.size());
    assertEndPoints(oval, simplifiedOval);
    assertSimplifiedPointsFromLine(oval, simplifiedOval);
    assertLineLength(oval, simplifiedOval);
    assertInputUnchanged(oval, copy);
}

25. PolyUtilTest#testDistanceToLine()

View license
public void testDistanceToLine() {
    LatLng startLine = new LatLng(28.05359, -82.41632);
    LatLng endLine = new LatLng(28.05310, -82.41634);
    LatLng p = new LatLng(28.05342, -82.41594);
    double distance = PolyUtil.distanceToLine(p, startLine, endLine);
    expectNearNumber(42.989894, distance, 1e-6);
}

26. SphericalUtilTest#testComputeOffsetAndBackToOrigin()

View license
public void testComputeOffsetAndBackToOrigin() {
    LatLng start = new LatLng(40, 40);
    double distance = 1e5;
    double heading = 15;
    LatLng end;
    // Some semi-random values to demonstrate going forward and backward yields
    // the same location.
    end = SphericalUtil.computeOffset(start, distance, heading);
    expectLatLngApproxEquals(start, SphericalUtil.computeOffsetOrigin(end, distance, heading));
    heading = -37;
    end = SphericalUtil.computeOffset(start, distance, heading);
    expectLatLngApproxEquals(start, SphericalUtil.computeOffsetOrigin(end, distance, heading));
    distance = 3.8e+7;
    end = SphericalUtil.computeOffset(start, distance, heading);
    expectLatLngApproxEquals(start, SphericalUtil.computeOffsetOrigin(end, distance, heading));
    start = new LatLng(-21, -73);
    end = SphericalUtil.computeOffset(start, distance, heading);
    expectLatLngApproxEquals(start, SphericalUtil.computeOffsetOrigin(end, distance, heading));
    // computeOffsetOrigin with multiple solutions, all we care about is that
    // going from there yields the requested result.
    //
    // First, for this particular situation the latitude is completely arbitrary.
    start = SphericalUtil.computeOffsetOrigin(new LatLng(0, 90), Math.PI * EARTH_RADIUS / 2, 90);
    expectLatLngApproxEquals(new LatLng(0, 90), SphericalUtil.computeOffset(start, Math.PI * EARTH_RADIUS / 2, 90));
    // Second, for this particular situation the longitude is completely
    // arbitrary.
    start = SphericalUtil.computeOffsetOrigin(new LatLng(90, 0), Math.PI * EARTH_RADIUS / 4, 0);
    expectLatLngApproxEquals(new LatLng(90, 0), SphericalUtil.computeOffset(start, Math.PI * EARTH_RADIUS / 4, 0));
}

27. PolyUtil#isClosedPolygon()

Project: android-maps-utils
Source File: PolyUtil.java
View license
/**
     * Returns true if the provided list of points is a closed polygon (i.e., the first and last
     * points are the same), and false if it is not
     * @param poly polyline or polygon
     * @return true if the provided list of points is a closed polygon (i.e., the first and last
     * points are the same), and false if it is not
     */
public static boolean isClosedPolygon(List<LatLng> poly) {
    LatLng firstPoint = poly.get(0);
    LatLng lastPoint = poly.get(poly.size() - 1);
    if (firstPoint.equals(lastPoint)) {
        return true;
    } else {
        return false;
    }
}

28. SphericalUtilTest#testComputeOffsetAndBackToOrigin()

View license
public void testComputeOffsetAndBackToOrigin() {
    LatLng start = new LatLng(40, 40);
    double distance = 1e5;
    double heading = 15;
    LatLng end;
    // Some semi-random values to demonstrate going forward and backward yields
    // the same location.
    end = SphericalUtil.computeOffset(start, distance, heading);
    expectLatLngApproxEquals(start, SphericalUtil.computeOffsetOrigin(end, distance, heading));
    heading = -37;
    end = SphericalUtil.computeOffset(start, distance, heading);
    expectLatLngApproxEquals(start, SphericalUtil.computeOffsetOrigin(end, distance, heading));
    distance = 3.8e+7;
    end = SphericalUtil.computeOffset(start, distance, heading);
    expectLatLngApproxEquals(start, SphericalUtil.computeOffsetOrigin(end, distance, heading));
    start = new LatLng(-21, -73);
    end = SphericalUtil.computeOffset(start, distance, heading);
    expectLatLngApproxEquals(start, SphericalUtil.computeOffsetOrigin(end, distance, heading));
    // computeOffsetOrigin with multiple solutions, all we care about is that
    // going from there yields the requested result.
    //
    // First, for this particular situation the latitude is completely arbitrary.
    start = SphericalUtil.computeOffsetOrigin(new LatLng(0, 90), Math.PI * EARTH_RADIUS / 2, 90);
    expectLatLngApproxEquals(new LatLng(0, 90), SphericalUtil.computeOffset(start, Math.PI * EARTH_RADIUS / 2, 90));
    // Second, for this particular situation the longitude is completely
    // arbitrary.
    start = SphericalUtil.computeOffsetOrigin(new LatLng(90, 0), Math.PI * EARTH_RADIUS / 4, 0);
    expectLatLngApproxEquals(new LatLng(90, 0), SphericalUtil.computeOffset(start, Math.PI * EARTH_RADIUS / 4, 0));
}

29. PolyUtilTest#testSimplify()

View license
public void testSimplify() {
    /**
         * Polyline
         */
    final String LINE = "elfjD~a}[email protected]@[email protected]^[email protected][email protected]`[email protected]{@DwCA{CF_EC{[email protected][email protected][email protected][email protected][email protected][email protected][email protected]@`@@[email protected][email protected][email protected][email protected]?vAH`@[email protected]^ETFJCLD?JA^?J?P?fAC`[email protected]@[email protected]\\@`@[email protected]@\\?`@[email protected][email protected][email protected]@@@[email protected]@[email protected][email protected]@[email protected]@@[email protected]@";
    List<LatLng> line = PolyUtil.decode(LINE);
    assertEquals(95, line.size());
    List<LatLng> simplifiedLine;
    List<LatLng> copy;
    // meters
    double tolerance = 5;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(21, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 10;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(14, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 15;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(10, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 20;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(8, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 50;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(6, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 500;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(3, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    // meters
    tolerance = 1000;
    copy = copyList(line);
    simplifiedLine = PolyUtil.simplify(line, tolerance);
    assertEquals(2, simplifiedLine.size());
    assertEndPoints(line, simplifiedLine);
    assertSimplifiedPointsFromLine(line, simplifiedLine);
    assertLineLength(line, simplifiedLine);
    assertInputUnchanged(line, copy);
    /**
         * Polygons
         */
    // Open triangle
    ArrayList<LatLng> triangle = new ArrayList<>();
    triangle.add(new LatLng(28.06025, -82.41030));
    triangle.add(new LatLng(28.06129, -82.40945));
    triangle.add(new LatLng(28.06206, -82.40917));
    triangle.add(new LatLng(28.06125, -82.40850));
    triangle.add(new LatLng(28.06035, -82.40834));
    triangle.add(new LatLng(28.06038, -82.40924));
    assertFalse(PolyUtil.isClosedPolygon(triangle));
    copy = copyList(triangle);
    // meters
    tolerance = 88;
    List simplifiedTriangle = PolyUtil.simplify(triangle, tolerance);
    assertEquals(4, simplifiedTriangle.size());
    assertEndPoints(triangle, simplifiedTriangle);
    assertSimplifiedPointsFromLine(triangle, simplifiedTriangle);
    assertLineLength(triangle, simplifiedTriangle);
    assertInputUnchanged(triangle, copy);
    // Close the triangle
    LatLng p = triangle.get(0);
    LatLng closePoint = new LatLng(p.latitude, p.longitude);
    triangle.add(closePoint);
    assertTrue(PolyUtil.isClosedPolygon(triangle));
    copy = copyList(triangle);
    // meters
    tolerance = 88;
    simplifiedTriangle = PolyUtil.simplify(triangle, tolerance);
    assertEquals(4, simplifiedTriangle.size());
    assertEndPoints(triangle, simplifiedTriangle);
    assertSimplifiedPointsFromLine(triangle, simplifiedTriangle);
    assertLineLength(triangle, simplifiedTriangle);
    assertInputUnchanged(triangle, copy);
    // Open oval
    final String OVAL_POLYGON = "}[email protected]}AN{A][email protected][email protected]?{@[email protected]@[email protected]]D[FULWFOLSNMTOVOXO\\I\\CX?VJXJTDTNXTVVLVJ`@FXA\\[email protected]?\\[email protected]";
    List<LatLng> oval = PolyUtil.decode(OVAL_POLYGON);
    assertFalse(PolyUtil.isClosedPolygon(oval));
    copy = copyList(oval);
    // meters
    tolerance = 10;
    List simplifiedOval = PolyUtil.simplify(oval, tolerance);
    assertEquals(13, simplifiedOval.size());
    assertEndPoints(oval, simplifiedOval);
    assertSimplifiedPointsFromLine(oval, simplifiedOval);
    assertLineLength(oval, simplifiedOval);
    assertInputUnchanged(oval, copy);
    // Close the oval
    p = oval.get(0);
    closePoint = new LatLng(p.latitude, p.longitude);
    oval.add(closePoint);
    assertTrue(PolyUtil.isClosedPolygon(oval));
    copy = copyList(oval);
    // meters
    tolerance = 10;
    simplifiedOval = PolyUtil.simplify(oval, tolerance);
    assertEquals(13, simplifiedOval.size());
    assertEndPoints(oval, simplifiedOval);
    assertSimplifiedPointsFromLine(oval, simplifiedOval);
    assertLineLength(oval, simplifiedOval);
    assertInputUnchanged(oval, copy);
}

30. PolyUtilTest#testDistanceToLine()

View license
public void testDistanceToLine() {
    LatLng startLine = new LatLng(28.05359, -82.41632);
    LatLng endLine = new LatLng(28.05310, -82.41634);
    LatLng p = new LatLng(28.05342, -82.41594);
    double distance = PolyUtil.distanceToLine(p, startLine, endLine);
    expectNearNumber(42.989894, distance, 1e-6);
}

31. PolyUtil#containsLocation()

Project: android-maps-utils
Source File: PolyUtil.java
View license
/**
     * Computes whether the given point lies inside the specified polygon.
     * The polygon is always cosidered closed, regardless of whether the last point equals
     * the first or not.
     * Inside is defined as not containing the South Pole -- the South Pole is always outside.
     * The polygon is formed of great circle segments if geodesic is true, and of rhumb
     * (loxodromic) segments otherwise.
     */
public static boolean containsLocation(LatLng point, List<LatLng> polygon, boolean geodesic) {
    final int size = polygon.size();
    if (size == 0) {
        return false;
    }
    double lat3 = toRadians(point.latitude);
    double lng3 = toRadians(point.longitude);
    LatLng prev = polygon.get(size - 1);
    double lat1 = toRadians(prev.latitude);
    double lng1 = toRadians(prev.longitude);
    int nIntersect = 0;
    for (LatLng point2 : polygon) {
        double dLng3 = wrap(lng3 - lng1, -PI, PI);
        // Special case: point equal to vertex is inside.
        if (lat3 == lat1 && dLng3 == 0) {
            return true;
        }
        double lat2 = toRadians(point2.latitude);
        double lng2 = toRadians(point2.longitude);
        // Offset longitudes by -lng1.
        if (intersects(lat1, lat2, wrap(lng2 - lng1, -PI, PI), lat3, dLng3, geodesic)) {
            ++nIntersect;
        }
        lat1 = lat2;
        lng1 = lng2;
    }
    return (nIntersect & 1) != 0;
}

32. PolyUtil#distanceToLine()

Project: android-maps-utils
Source File: PolyUtil.java
View license
/**
     * Computes the distance on the sphere between the point p and the line segment start to end.
     *
     * @param p the point to be measured
     * @param start the beginning of the line segment
     * @param end the end of the line segment
     * @return the distance in meters (assuming spherical earth)
     */
public static double distanceToLine(final LatLng p, final LatLng start, final LatLng end) {
    if (start.equals(end)) {
        computeDistanceBetween(end, p);
    }
    final double s0lat = toRadians(p.latitude);
    final double s0lng = toRadians(p.longitude);
    final double s1lat = toRadians(start.latitude);
    final double s1lng = toRadians(start.longitude);
    final double s2lat = toRadians(end.latitude);
    final double s2lng = toRadians(end.longitude);
    double s2s1lat = s2lat - s1lat;
    double s2s1lng = s2lng - s1lng;
    final double u = ((s0lat - s1lat) * s2s1lat + (s0lng - s1lng) * s2s1lng) / (s2s1lat * s2s1lat + s2s1lng * s2s1lng);
    if (u <= 0) {
        return computeDistanceBetween(p, start);
    }
    if (u >= 1) {
        return computeDistanceBetween(p, end);
    }
    LatLng sa = new LatLng(p.latitude - start.latitude, p.longitude - start.longitude);
    LatLng sb = new LatLng(u * (end.latitude - start.latitude), u * (end.longitude - start.longitude));
    return computeDistanceBetween(sa, sb);
}

33. PolyUtilTest#containsCase()

View license
private static void containsCase(List<LatLng> poly, List<LatLng> yes, List<LatLng> no) {
    for (LatLng point : yes) {
        Assert.assertTrue(PolyUtil.containsLocation(point, poly, true));
        Assert.assertTrue(PolyUtil.containsLocation(point, poly, false));
    }
    for (LatLng point : no) {
        Assert.assertFalse(PolyUtil.containsLocation(point, poly, true));
        Assert.assertFalse(PolyUtil.containsLocation(point, poly, false));
    }
}

34. GeoJsonParser#parseBoundingBox()

View license
/**
     * Parses a bounding box given as a JSONArray of 4 elements in the order of lowest values for
     * all axes followed by highest values. Axes order of a bounding box follows the axes order of
     * geometries.
     *
     * @param coordinates array of 4 coordinates
     * @return LatLngBounds containing the coordinates of the bounding box
     * @throws JSONException if the bounding box could not be parsed
     */
private static LatLngBounds parseBoundingBox(JSONArray coordinates) throws JSONException {
    // Lowest values for all axes
    LatLng southWestCorner = new LatLng(coordinates.getDouble(1), coordinates.getDouble(0));
    // Highest value for all axes
    LatLng northEastCorner = new LatLng(coordinates.getDouble(3), coordinates.getDouble(2));
    return new LatLngBounds(southWestCorner, northEastCorner);
}

35. ExploreFragment#getRadiusFromMapProjection()

Project: rox-android
Source File: ExploreFragment.java
View license
private int getRadiusFromMapProjection() {
    LatLng point1 = googleMap.getProjection().getVisibleRegion().nearLeft;
    LatLng point2 = googleMap.getProjection().getVisibleRegion().nearRight;
    float[] results = new float[1];
    Location.distanceBetween(point1.latitude, point1.longitude, point2.latitude, point2.longitude, results);
    return Math.round(results[0] / 2f);
}

36. PolyUtilTest#onEdgeCase()

View license
private static void onEdgeCase(boolean geodesic, List<LatLng> poly, List<LatLng> yes, List<LatLng> no) {
    for (LatLng point : yes) {
        Assert.assertTrue(PolyUtil.isLocationOnEdge(point, poly, geodesic));
        Assert.assertTrue(PolyUtil.isLocationOnPath(point, poly, geodesic));
    }
    for (LatLng point : no) {
        Assert.assertFalse(PolyUtil.isLocationOnEdge(point, poly, geodesic));
        Assert.assertFalse(PolyUtil.isLocationOnPath(point, poly, geodesic));
    }
}

37. KmlFeatureParser#createLatLngBounds()

View license
/**
     * Given a set of four latLng coordinates, creates a LatLng Bound
     *
     * @param north North coordinate of the bounding box
     * @param south South coordinate of the bounding box
     * @param east  East coordinate of the bounding box
     * @param west  West coordinate of the bounding box
     */
private static LatLngBounds createLatLngBounds(Double north, Double south, Double east, Double west) {
    LatLng southWest = new LatLng(south, west);
    LatLng northEast = new LatLng(north, east);
    return new LatLngBounds(southWest, northEast);
}

38. PolyUtil#containsLocation()

Project: wigle-wifi-wardriving
Source File: PolyUtil.java
View license
/**
     * Computes whether the given point lies inside the specified polygon.
     * The polygon is always cosidered closed, regardless of whether the last point equals
     * the first or not.
     * Inside is defined as not containing the South Pole -- the South Pole is always outside.
     * The polygon is formed of great circle segments if geodesic is true, and of rhumb
     * (loxodromic) segments otherwise.
     */
public static boolean containsLocation(LatLng point, List<LatLng> polygon, boolean geodesic) {
    final int size = polygon.size();
    if (size == 0) {
        return false;
    }
    double lat3 = toRadians(point.latitude);
    double lng3 = toRadians(point.longitude);
    LatLng prev = polygon.get(size - 1);
    double lat1 = toRadians(prev.latitude);
    double lng1 = toRadians(prev.longitude);
    int nIntersect = 0;
    for (LatLng point2 : polygon) {
        double dLng3 = wrap(lng3 - lng1, -PI, PI);
        // Special case: point equal to vertex is inside.
        if (lat3 == lat1 && dLng3 == 0) {
            return true;
        }
        double lat2 = toRadians(point2.latitude);
        double lng2 = toRadians(point2.longitude);
        // Offset longitudes by -lng1.
        if (intersects(lat1, lat2, wrap(lng2 - lng1, -PI, PI), lat3, dLng3, geodesic)) {
            ++nIntersect;
        }
        lat1 = lat2;
        lng1 = lng2;
    }
    return (nIntersect & 1) != 0;
}

39. PolyUtil#simplify()

Project: wigle-wifi-wardriving
Source File: PolyUtil.java
View license
/**
     * Simplifies the given poly (polyline or polygon) using the Douglas-Peucker decimation
     * algorithm.  Increasing the tolerance will result in fewer points in the simplified polyline
     * or polygon.
     *
     * When the providing a polygon as input, the first and last point of the list MUST have the
     * same latitude and longitude (i.e., the polygon must be closed).  If the input polygon is not
     * closed, the resulting polygon may not be fully simplified.
     *
     * The time complexity of Douglas-Peucker is O(n^2), so take care that you do not call this
     * algorithm too frequently in your code.
     *
     * @param poly polyline or polygon to be simplified.  Polygon should be closed (i.e.,
     *              first and last points should have the same latitude and longitude).
     * @param tolerance in meters.  Increasing the tolerance will result in fewer points in the
     *                  simplified poly.
     * @return a simplified poly produced by the Douglas-Peucker algorithm
     */
public static List<LatLng> simplify(List<LatLng> poly, double tolerance) {
    final int n = poly.size();
    if (n < 1) {
        throw new IllegalArgumentException("Polyline must have at least 1 point");
    }
    if (tolerance <= 0) {
        throw new IllegalArgumentException("Tolerance must be greater than zero");
    }
    boolean closedPolygon = isClosedPolygon(poly);
    LatLng lastPoint = null;
    // Check if the provided poly is a closed polygon
    if (closedPolygon) {
        // Add a small offset to the last point for Douglas-Peucker on polygons (see #201)
        final double OFFSET = 0.00000000001;
        lastPoint = poly.get(poly.size() - 1);
        // LatLng.latitude and .longitude are immutable, so replace the last point
        poly.remove(poly.size() - 1);
        poly.add(new LatLng(lastPoint.latitude + OFFSET, lastPoint.longitude + OFFSET));
    }
    int idx;
    int maxIdx = 0;
    Stack<int[]> stack = new Stack<>();
    double[] dists = new double[n];
    dists[0] = 1;
    dists[n - 1] = 1;
    double maxDist;
    double dist = 0.0;
    int[] current;
    if (n > 2) {
        int[] stackVal = new int[] { 0, (n - 1) };
        stack.push(stackVal);
        while (stack.size() > 0) {
            current = stack.pop();
            maxDist = 0;
            for (idx = current[0] + 1; idx < current[1]; ++idx) {
                dist = distanceToLine(poly.get(idx), poly.get(current[0]), poly.get(current[1]));
                if (dist > maxDist) {
                    maxDist = dist;
                    maxIdx = idx;
                }
            }
            if (maxDist > tolerance) {
                dists[maxIdx] = maxDist;
                int[] stackValCurMax = { current[0], maxIdx };
                stack.push(stackValCurMax);
                int[] stackValMaxCur = { maxIdx, current[1] };
                stack.push(stackValMaxCur);
            }
        }
    }
    if (closedPolygon) {
        // Replace last point w/ offset with the original last point to re-close the polygon
        poly.remove(poly.size() - 1);
        poly.add(lastPoint);
    }
    // Generate the simplified line
    idx = 0;
    ArrayList<LatLng> simplifiedLine = new ArrayList<>();
    for (LatLng l : poly) {
        if (dists[idx] != 0) {
            simplifiedLine.add(l);
        }
        idx++;
    }
    return simplifiedLine;
}

40. PolyUtil#simplify()

Project: android-maps-utils
Source File: PolyUtil.java
View license
/**
     * Simplifies the given poly (polyline or polygon) using the Douglas-Peucker decimation
     * algorithm.  Increasing the tolerance will result in fewer points in the simplified polyline
     * or polygon.
     *
     * When the providing a polygon as input, the first and last point of the list MUST have the
     * same latitude and longitude (i.e., the polygon must be closed).  If the input polygon is not
     * closed, the resulting polygon may not be fully simplified.
     *
     * The time complexity of Douglas-Peucker is O(n^2), so take care that you do not call this
     * algorithm too frequently in your code.
     *
     * @param poly polyline or polygon to be simplified.  Polygon should be closed (i.e.,
     *              first and last points should have the same latitude and longitude).
     * @param tolerance in meters.  Increasing the tolerance will result in fewer points in the
     *                  simplified poly.
     * @return a simplified poly produced by the Douglas-Peucker algorithm
     */
public static List<LatLng> simplify(List<LatLng> poly, double tolerance) {
    final int n = poly.size();
    if (n < 1) {
        throw new IllegalArgumentException("Polyline must have at least 1 point");
    }
    if (tolerance <= 0) {
        throw new IllegalArgumentException("Tolerance must be greater than zero");
    }
    boolean closedPolygon = isClosedPolygon(poly);
    LatLng lastPoint = null;
    // Check if the provided poly is a closed polygon
    if (closedPolygon) {
        // Add a small offset to the last point for Douglas-Peucker on polygons (see #201)
        final double OFFSET = 0.00000000001;
        lastPoint = poly.get(poly.size() - 1);
        // LatLng.latitude and .longitude are immutable, so replace the last point
        poly.remove(poly.size() - 1);
        poly.add(new LatLng(lastPoint.latitude + OFFSET, lastPoint.longitude + OFFSET));
    }
    int idx;
    int maxIdx = 0;
    Stack<int[]> stack = new Stack<>();
    double[] dists = new double[n];
    dists[0] = 1;
    dists[n - 1] = 1;
    double maxDist;
    double dist = 0.0;
    int[] current;
    if (n > 2) {
        int[] stackVal = new int[] { 0, (n - 1) };
        stack.push(stackVal);
        while (stack.size() > 0) {
            current = stack.pop();
            maxDist = 0;
            for (idx = current[0] + 1; idx < current[1]; ++idx) {
                dist = distanceToLine(poly.get(idx), poly.get(current[0]), poly.get(current[1]));
                if (dist > maxDist) {
                    maxDist = dist;
                    maxIdx = idx;
                }
            }
            if (maxDist > tolerance) {
                dists[maxIdx] = maxDist;
                int[] stackValCurMax = { current[0], maxIdx };
                stack.push(stackValCurMax);
                int[] stackValMaxCur = { maxIdx, current[1] };
                stack.push(stackValMaxCur);
            }
        }
    }
    if (closedPolygon) {
        // Replace last point w/ offset with the original last point to re-close the polygon
        poly.remove(poly.size() - 1);
        poly.add(lastPoint);
    }
    // Generate the simplified line
    idx = 0;
    ArrayList<LatLng> simplifiedLine = new ArrayList<>();
    for (LatLng l : poly) {
        if (dists[idx] != 0) {
            simplifiedLine.add(l);
        }
        idx++;
    }
    return simplifiedLine;
}

41. PolyUtil#distanceToLine()

Project: wigle-wifi-wardriving
Source File: PolyUtil.java
View license
/**
     * Computes the distance on the sphere between the point p and the line segment start to end.
     *
     * @param p the point to be measured
     * @param start the beginning of the line segment
     * @param end the end of the line segment
     * @return the distance in meters (assuming spherical earth)
     */
public static double distanceToLine(final LatLng p, final LatLng start, final LatLng end) {
    if (start.equals(end)) {
        computeDistanceBetween(end, p);
    }
    final double s0lat = toRadians(p.latitude);
    final double s0lng = toRadians(p.longitude);
    final double s1lat = toRadians(start.latitude);
    final double s1lng = toRadians(start.longitude);
    final double s2lat = toRadians(end.latitude);
    final double s2lng = toRadians(end.longitude);
    double s2s1lat = s2lat - s1lat;
    double s2s1lng = s2lng - s1lng;
    final double u = ((s0lat - s1lat) * s2s1lat + (s0lng - s1lng) * s2s1lng) / (s2s1lat * s2s1lat + s2s1lng * s2s1lng);
    if (u <= 0) {
        return computeDistanceBetween(p, start);
    }
    if (u >= 1) {
        return computeDistanceBetween(p, end);
    }
    LatLng sa = new LatLng(p.latitude - start.latitude, p.longitude - start.longitude);
    LatLng sb = new LatLng(u * (end.latitude - start.latitude), u * (end.longitude - start.longitude));
    return computeDistanceBetween(sa, sb);
}

42. PolyUtilTest#containsCase()

View license
private static void containsCase(List<LatLng> poly, List<LatLng> yes, List<LatLng> no) {
    for (LatLng point : yes) {
        Assert.assertTrue(PolyUtil.containsLocation(point, poly, true));
        Assert.assertTrue(PolyUtil.containsLocation(point, poly, false));
    }
    for (LatLng point : no) {
        Assert.assertFalse(PolyUtil.containsLocation(point, poly, true));
        Assert.assertFalse(PolyUtil.containsLocation(point, poly, false));
    }
}

43. PolyUtilTest#onEdgeCase()

View license
private static void onEdgeCase(boolean geodesic, List<LatLng> poly, List<LatLng> yes, List<LatLng> no) {
    for (LatLng point : yes) {
        Assert.assertTrue(PolyUtil.isLocationOnEdge(point, poly, geodesic));
        Assert.assertTrue(PolyUtil.isLocationOnPath(point, poly, geodesic));
    }
    for (LatLng point : no) {
        Assert.assertFalse(PolyUtil.isLocationOnEdge(point, poly, geodesic));
        Assert.assertFalse(PolyUtil.isLocationOnPath(point, poly, geodesic));
    }
}

44. MainActivity#generateOfferObject()

Project: io2014-codelabs
Source File: MainActivity.java
View license
public OfferWalletObject generateOfferObject() {
    //Image Uris
    List<UriData> imageUris = new ArrayList<UriData>();
    UriData imageUri = new UriData("https://www.google.com/events/io/images/photos/LogisticsGettingAround-1600.jpg", "San Francisco");
    imageUris.add(imageUri);
    //Geolocations
    LatLng google = new LatLng(37.422601, -122.085286);
    LatLng mosconeWest = new LatLng(37.7842, -122.4016);
    List<LatLng> locations = new ArrayList<LatLng>();
    locations.add(google);
    locations.add(mosconeWest);
    //URIs
    UriData mosconeWestMaps = new UriData("http://maps.google.com/maps?q=moscone%20west", "Moscone West");
    UriData googleIo = new UriData("http://google.com/io", "Google I/O");
    List<UriData> uris = new ArrayList<UriData>();
    uris.add(mosconeWestMaps);
    uris.add(googleIo);
    OfferWalletObject offerWalletObject = OfferWalletObject.newBuilder().setClassId("2979629121142263025.OfferClassIO").setId("2979629121142263025.OfferOfferObjectIO").setState(WalletObjectsConstants.State.ACTIVE).setIssuerName("Google I/O Demo").setTitle("20% off Code Labs").setBarcodeType("qrCode").setBarcodeValue("28343E3").setBarcodeAlternateText("12345").setBarcodeLabel("Coupon Code").addLinksModuleDataUris(uris).addImageModuleDataMainImageUris(imageUris).addLocations(locations).build();
    return offerWalletObject;
}

45. KmlFeatureParser#createLatLngBounds()

View license
/**
     * Given a set of four latLng coordinates, creates a LatLng Bound
     *
     * @param north North coordinate of the bounding box
     * @param south South coordinate of the bounding box
     * @param east  East coordinate of the bounding box
     * @param west  West coordinate of the bounding box
     */
private static LatLngBounds createLatLngBounds(Double north, Double south, Double east, Double west) {
    LatLng southWest = new LatLng(south, west);
    LatLng northEast = new LatLng(north, east);
    return new LatLngBounds(southWest, northEast);
}

46. Routing#constructURL()

View license
protected String constructURL() {
    final StringBuilder stringBuilder = new StringBuilder(AbstractRouting.DIRECTIONS_API_URL);
    // origin
    final LatLng origin = waypoints.get(0);
    stringBuilder.append("origin=").append(origin.latitude).append(',').append(origin.longitude);
    // destination
    final LatLng destination = waypoints.get(waypoints.size() - 1);
    stringBuilder.append("&destination=").append(destination.latitude).append(',').append(destination.longitude);
    // travel
    stringBuilder.append("&mode=").append(travelMode.getValue());
    // waypoints
    if (waypoints.size() > 2) {
        stringBuilder.append("&waypoints=");
        if (optimize)
            stringBuilder.append("optimize:true|");
        for (int i = 1; i < waypoints.size() - 1; i++) {
            final LatLng p = waypoints.get(i);
            // we don't want to parse the resulting JSON for 'legs'.
            stringBuilder.append("via:");
            stringBuilder.append(p.latitude);
            stringBuilder.append(',');
            stringBuilder.append(p.longitude);
            stringBuilder.append('|');
        }
    }
    // avoid
    if (avoidKinds > 0) {
        stringBuilder.append("&avoid=");
        stringBuilder.append(AvoidKind.getRequestParam(avoidKinds));
    }
    if (alternativeRoutes) {
        stringBuilder.append("&alternatives=true");
    }
    // sensor
    stringBuilder.append("&sensor=true");
    // language
    if (language != null) {
        stringBuilder.append("&language=").append(language);
    }
    // API key
    if (key != null) {
        stringBuilder.append("&key=").append(key);
    }
    return stringBuilder.toString();
}

47. GeoJsonParser#parseBoundingBox()

View license
/**
     * Parses a bounding box given as a JSONArray of 4 elements in the order of lowest values for
     * all axes followed by highest values. Axes order of a bounding box follows the axes order of
     * geometries.
     *
     * @param coordinates array of 4 coordinates
     * @return LatLngBounds containing the coordinates of the bounding box
     * @throws JSONException if the bounding box could not be parsed
     */
private static LatLngBounds parseBoundingBox(JSONArray coordinates) throws JSONException {
    // Lowest values for all axes
    LatLng southWestCorner = new LatLng(coordinates.getDouble(1), coordinates.getDouble(0));
    // Highest value for all axes
    LatLng northEastCorner = new LatLng(coordinates.getDouble(3), coordinates.getDouble(2));
    return new LatLngBounds(southWestCorner, northEastCorner);
}

48. PolyUtilTest#copyList()

View license
/**
     * Returns a copy of the LatLng objects contained in one list to another list.  LatLng.latitude
     * and LatLng.longitude are immutable, so having references to the same LatLng object is
     * sufficient to guarantee that the contents are the same.
     * @param original original list
     * @return a copy of the original list, containing references to the same LatLng elements in
     * the same order.
     */
private List<LatLng> copyList(List<LatLng> original) {
    ArrayList<LatLng> copy = new ArrayList<>(original.size());
    for (LatLng l : original) {
        copy.add(l);
    }
    return copy;
}

49. MappingFragment#getCenter()

View license
public static LatLng getCenter(final Context context, final LatLng priorityCenter, final Location previousLocation) {
    LatLng centerPoint = DEFAULT_POINT;
    final Location location = ListFragment.lameStatic.location;
    final SharedPreferences prefs = context.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
    if (priorityCenter != null) {
        centerPoint = priorityCenter;
    } else if (location != null) {
        centerPoint = new LatLng(location.getLatitude(), location.getLongitude());
    } else if (previousLocation != null) {
        centerPoint = new LatLng(previousLocation.getLatitude(), previousLocation.getLongitude());
    } else {
        final Location gpsLocation = safelyGetLast(context, LocationManager.GPS_PROVIDER);
        final Location networkLocation = safelyGetLast(context, LocationManager.NETWORK_PROVIDER);
        if (gpsLocation != null) {
            centerPoint = new LatLng(gpsLocation.getLatitude(), gpsLocation.getLongitude());
        } else if (networkLocation != null) {
            centerPoint = new LatLng(networkLocation.getLatitude(), networkLocation.getLongitude());
        } else {
            // ok, try the saved prefs
            float lat = prefs.getFloat(ListFragment.PREF_PREV_LAT, Float.MIN_VALUE);
            float lon = prefs.getFloat(ListFragment.PREF_PREV_LON, Float.MIN_VALUE);
            if (lat != Float.MIN_VALUE && lon != Float.MIN_VALUE) {
                centerPoint = new LatLng(lat, lon);
            }
        }
    }
    return centerPoint;
}

50. WebViewMapFragment#addMarker()

Project: AirMapView
Source File: WebViewMapFragment.java
View license
@Override
public void addMarker(AirMapMarker<?> marker) {
    LatLng latLng = marker.getLatLng();
    markers.put(marker.getId(), marker);
    webView.loadUrl(String.format(Locale.US, "javascript:addMarkerWithId(%1$f, %2$f, %3$d, '%4$s', '%5$s', %6$b);", latLng.latitude, latLng.longitude, marker.getId(), marker.getTitle(), marker.getSnippet(), marker.getMarkerOptions().isDraggable()));
}

51. GoogleMapFragment#getBounds()

Project: Tower
Source File: GoogleMapFragment.java
View license
private LatLngBounds getBounds(List<LatLng> pointsList) {
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (LatLng point : pointsList) {
        builder.include(point);
    }
    return builder.build();
}

52. DirectionConverter#createPolyline()

View license
public static PolylineOptions createPolyline(Context context, ArrayList<LatLng> locationList, int width, int color) {
    PolylineOptions rectLine = new PolylineOptions().width(dpToPx(context, width)).color(color).geodesic(true);
    for (LatLng location : locationList) {
        rectLine.add(location);
    }
    return rectLine;
}

53. HeatmapTileProvider#wrapData()

View license
/**
     * Helper function - wraps LatLngs into WeightedLatLngs.
     *
     * @param data Data to wrap (LatLng)
     * @return Data, in WeightedLatLng form
     */
private static Collection<WeightedLatLng> wrapData(Collection<LatLng> data) {
    // Use an ArrayList as it is a nice collection
    ArrayList<WeightedLatLng> weightedData = new ArrayList<WeightedLatLng>();
    for (LatLng l : data) {
        weightedData.add(new WeightedLatLng(l));
    }
    return weightedData;
}

54. PolyUtilTest#testDecodePath()

View license
public void testDecodePath() {
    List<LatLng> latLngs = PolyUtil.decode(TEST_LINE);
    int expectedLength = 21;
    Assert.assertEquals("Wrong length.", expectedLength, latLngs.size());
    LatLng lastPoint = latLngs.get(expectedLength - 1);
    expectNearNumber(37.76953, lastPoint.latitude, 1e-6);
    expectNearNumber(-122.41488, lastPoint.longitude, 1e-6);
}

55. PolyUtilTest#assertSimplifiedPointsFromLine()

View license
/**
     * Asserts that the simplified line is composed of points from the original line.
     * @param line original line
     * @param simplifiedLine simplified line
     */
private void assertSimplifiedPointsFromLine(List<LatLng> line, List<LatLng> simplifiedLine) {
    for (LatLng l : simplifiedLine) {
        assertTrue(line.contains(l));
    }
}

56. PolyUtil#isLocationOnEdgeOrPath()

Project: wigle-wifi-wardriving
Source File: PolyUtil.java
View license
private static boolean isLocationOnEdgeOrPath(LatLng point, List<LatLng> poly, boolean closed, boolean geodesic, double toleranceEarth) {
    int size = poly.size();
    if (size == 0) {
        return false;
    }
    double tolerance = toleranceEarth / EARTH_RADIUS;
    double havTolerance = hav(tolerance);
    double lat3 = toRadians(point.latitude);
    double lng3 = toRadians(point.longitude);
    LatLng prev = poly.get(closed ? size - 1 : 0);
    double lat1 = toRadians(prev.latitude);
    double lng1 = toRadians(prev.longitude);
    if (geodesic) {
        for (LatLng point2 : poly) {
            double lat2 = toRadians(point2.latitude);
            double lng2 = toRadians(point2.longitude);
            if (isOnSegmentGC(lat1, lng1, lat2, lng2, lat3, lng3, havTolerance)) {
                return true;
            }
            lat1 = lat2;
            lng1 = lng2;
        }
    } else {
        // We project the points to mercator space, where the Rhumb segment is a straight line,
        // and compute the geodesic distance between point3 and the closest point on the
        // segment. This method is an approximation, because it uses "closest" in mercator
        // space which is not "closest" on the sphere -- but the error is small because
        // "tolerance" is small.
        double minAcceptable = lat3 - tolerance;
        double maxAcceptable = lat3 + tolerance;
        double y1 = mercator(lat1);
        double y3 = mercator(lat3);
        double[] xTry = new double[3];
        for (LatLng point2 : poly) {
            double lat2 = toRadians(point2.latitude);
            double y2 = mercator(lat2);
            double lng2 = toRadians(point2.longitude);
            if (max(lat1, lat2) >= minAcceptable && min(lat1, lat2) <= maxAcceptable) {
                // We offset longitudes by -lng1; the implicit x1 is 0.
                double x2 = wrap(lng2 - lng1, -PI, PI);
                double x3Base = wrap(lng3 - lng1, -PI, PI);
                xTry[0] = x3Base;
                // Also explore wrapping of x3Base around the world in both directions.
                xTry[1] = x3Base + 2 * PI;
                xTry[2] = x3Base - 2 * PI;
                for (double x3 : xTry) {
                    double dy = y2 - y1;
                    double len2 = x2 * x2 + dy * dy;
                    double t = len2 <= 0 ? 0 : clamp((x3 * x2 + (y3 - y1) * dy) / len2, 0, 1);
                    double xClosest = t * x2;
                    double yClosest = y1 + t * dy;
                    double latClosest = inverseMercator(yClosest);
                    double havDist = havDistance(lat3, latClosest, x3 - xClosest);
                    if (havDist < havTolerance) {
                        return true;
                    }
                }
            }
            lat1 = lat2;
            lng1 = lng2;
            y1 = y2;
        }
    }
    return false;
}

57. HeatmapTileProvider#wrapData()

View license
/**
     * Helper function - wraps LatLngs into WeightedLatLngs.
     *
     * @param data Data to wrap (LatLng)
     * @return Data, in WeightedLatLng form
     */
private static Collection<WeightedLatLng> wrapData(Collection<LatLng> data) {
    // Use an ArrayList as it is a nice collection
    ArrayList<WeightedLatLng> weightedData = new ArrayList<WeightedLatLng>();
    for (LatLng l : data) {
        weightedData.add(new WeightedLatLng(l));
    }
    return weightedData;
}

58. PolyUtil#isLocationOnEdgeOrPath()

Project: android-maps-utils
Source File: PolyUtil.java
View license
private static boolean isLocationOnEdgeOrPath(LatLng point, List<LatLng> poly, boolean closed, boolean geodesic, double toleranceEarth) {
    int size = poly.size();
    if (size == 0) {
        return false;
    }
    double tolerance = toleranceEarth / EARTH_RADIUS;
    double havTolerance = hav(tolerance);
    double lat3 = toRadians(point.latitude);
    double lng3 = toRadians(point.longitude);
    LatLng prev = poly.get(closed ? size - 1 : 0);
    double lat1 = toRadians(prev.latitude);
    double lng1 = toRadians(prev.longitude);
    if (geodesic) {
        for (LatLng point2 : poly) {
            double lat2 = toRadians(point2.latitude);
            double lng2 = toRadians(point2.longitude);
            if (isOnSegmentGC(lat1, lng1, lat2, lng2, lat3, lng3, havTolerance)) {
                return true;
            }
            lat1 = lat2;
            lng1 = lng2;
        }
    } else {
        // We project the points to mercator space, where the Rhumb segment is a straight line,
        // and compute the geodesic distance between point3 and the closest point on the
        // segment. This method is an approximation, because it uses "closest" in mercator
        // space which is not "closest" on the sphere -- but the error is small because
        // "tolerance" is small.
        double minAcceptable = lat3 - tolerance;
        double maxAcceptable = lat3 + tolerance;
        double y1 = mercator(lat1);
        double y3 = mercator(lat3);
        double[] xTry = new double[3];
        for (LatLng point2 : poly) {
            double lat2 = toRadians(point2.latitude);
            double y2 = mercator(lat2);
            double lng2 = toRadians(point2.longitude);
            if (max(lat1, lat2) >= minAcceptable && min(lat1, lat2) <= maxAcceptable) {
                // We offset longitudes by -lng1; the implicit x1 is 0.
                double x2 = wrap(lng2 - lng1, -PI, PI);
                double x3Base = wrap(lng3 - lng1, -PI, PI);
                xTry[0] = x3Base;
                // Also explore wrapping of x3Base around the world in both directions.
                xTry[1] = x3Base + 2 * PI;
                xTry[2] = x3Base - 2 * PI;
                for (double x3 : xTry) {
                    double dy = y2 - y1;
                    double len2 = x2 * x2 + dy * dy;
                    double t = len2 <= 0 ? 0 : clamp((x3 * x2 + (y3 - y1) * dy) / len2, 0, 1);
                    double xClosest = t * x2;
                    double yClosest = y1 + t * dy;
                    double latClosest = inverseMercator(yClosest);
                    double havDist = havDistance(lat3, latClosest, x3 - xClosest);
                    if (havDist < havTolerance) {
                        return true;
                    }
                }
            }
            lat1 = lat2;
            lng1 = lng2;
            y1 = y2;
        }
    }
    return false;
}

59. MapsActivity#onMapReady()

Project: ScreenshotsNanny
Source File: MapsActivity.java
View license
@Override
public void onMapReady(GoogleMap googleMap) {
    LatLng berlin = new LatLng(mBerlinLat, mBerlinLng);
    Marker marker = googleMap.addMarker(new MarkerOptions().position(berlin).title(getString(R.string.map_marker_title)));
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(berlin));
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(mBerlinZoomLevel));
    mEditTextLat.setText(String.valueOf(marker.getPosition().latitude));
    mEditTextLng.setText(String.valueOf(marker.getPosition().longitude));
}

60. NearByVehicleActivity#setUpMap()

View license
private void setUpMap() {
    AppLog.enter(TAG, AppLog.getMethodName());
    Vehicle currentVehicle = FordDemoUtil.getInstance().getVehicle();
    double srclat = 0.0;
    double srclng = 0.0;
    try {
        srclat = Double.parseDouble(currentVehicle.getLatitude());
        srclng = Double.parseDouble(currentVehicle.getLongitude());
    } catch (NumberFormatException ex) {
        AppLog.error(TAG, "Error : " + ex.toString());
        return;
    }
    LatLng origin = new LatLng(srclat, srclng);
    mCurrentVehicleMarker = mGoogleMap.addMarker(new MarkerOptions().position(origin).icon(BitmapDescriptorFactory.fromResource(R.drawable.current_vehicle)));
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(origin, 15));
    moveCarLocation();
    mNearByVehiclesRetriverTask = new NearByVehiclesRetriverTask(this);
    mNearByVehiclesRetriverTask.execute();
    AppLog.exit(TAG, AppLog.getMethodName());
}

61. MainFragment#moveToLocation()

View license
private void moveToLocation(Location location) {
    if (location == null) {
        return;
    }
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    moveToLocation(latLng);
}

62. CameraPositionAssert#hasTarget()

View license
public CameraPositionAssert hasTarget(LatLng target) {
    isNotNull();
    LatLng actualTarget = actual.target;
    //
    assertThat(actualTarget).overridingErrorMessage("Expected target <%s> but was <%s>.", target, //
    actualTarget).isEqualTo(target);
    return this;
}

63. MarkerAssert#hasPosition()

Project: assertj-android
Source File: MarkerAssert.java
View license
public MarkerAssert hasPosition(LatLng position) {
    isNotNull();
    LatLng actualLatLng = actual.getPosition();
    //
    assertThat(actualLatLng).overridingErrorMessage("Expected position <%s> but was <%s>.", position, //
    actualLatLng).isEqualTo(position);
    return this;
}

64. MapsActivity#onMapReady()

Project: CMRU-run
Source File: MapsActivity.java
View license
/**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

65. TripMapActivity#addStationMarker()

Project: farebot
Source File: TripMapActivity.java
View license
private LatLng addStationMarker(Station station, int iconId) {
    LatLng pos = new LatLng(Double.valueOf(station.getLatitude()), Double.valueOf(station.getLongitude()));
    mMap.addMarker(new MarkerOptions().position(pos).title(station.getStationName()).snippet(station.getCompanyName()).icon(BitmapDescriptorFactory.fromResource(iconId)));
    return pos;
}

66. DetailActivity#setupMap()

Project: google-io-2014
Source File: DetailActivity.java
View license
private void setupMap() {
    GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    double lat = getIntent().getDoubleExtra("lat", 37.6329946);
    double lng = getIntent().getDoubleExtra("lng", -122.4938344);
    float zoom = getIntent().getFloatExtra("zoom", 15.0f);
    LatLng position = new LatLng(lat, lng);
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, zoom));
    map.addMarker(new MarkerOptions().position(position));
}

67. PolyUtilTest#testDecodePath()

View license
public void testDecodePath() {
    List<LatLng> latLngs = PolyUtil.decode(TEST_LINE);
    int expectedLength = 21;
    Assert.assertEquals("Wrong length.", expectedLength, latLngs.size());
    LatLng lastPoint = latLngs.get(expectedLength - 1);
    expectNearNumber(37.76953, lastPoint.latitude, 1e-6);
    expectNearNumber(-122.41488, lastPoint.longitude, 1e-6);
}

68. DetailFragment#onCreateView()

Project: io2015-codelabs
Source File: DetailFragment.java
View license
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    View view = inflater.inflate(R.layout.fragment_detail, container, false);
    String attractionName = getArguments().getString(EXTRA_ATTRACTION);
    mAttraction = findAttraction(attractionName);
    if (mAttraction == null) {
        getActivity().finish();
        return null;
    }
    TextView nameTextView = (TextView) view.findViewById(R.id.nameTextView);
    TextView descTextView = (TextView) view.findViewById(R.id.descriptionTextView);
    TextView distanceTextView = (TextView) view.findViewById(R.id.distanceTextView);
    ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
    LatLng location = Utils.getLocation(getActivity());
    String distance = Utils.formatDistanceBetween(location, mAttraction.location);
    if (TextUtils.isEmpty(distance)) {
        distanceTextView.setVisibility(View.GONE);
    }
    nameTextView.setText(attractionName);
    distanceTextView.setText(distance);
    descTextView.setText(mAttraction.longDescription);
    int imageSize = getResources().getDimensionPixelSize(R.dimen.image_size) * Constants.IMAGE_ANIM_MULTIPLIER;
    Glide.with(getActivity()).load(mAttraction.imageUrl).diskCacheStrategy(DiskCacheStrategy.SOURCE).placeholder(R.color.lighter_gray).override(imageSize, imageSize).into(imageView);
    return view;
}

69. DetailFragment#onCreateView()

Project: io2015-codelabs
Source File: DetailFragment.java
View license
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    View view = inflater.inflate(R.layout.fragment_detail, container, false);
    String attractionName = getArguments().getString(EXTRA_ATTRACTION);
    mAttraction = findAttraction(attractionName);
    if (mAttraction == null) {
        getActivity().finish();
        return null;
    }
    TextView nameTextView = (TextView) view.findViewById(R.id.nameTextView);
    TextView descTextView = (TextView) view.findViewById(R.id.descriptionTextView);
    TextView distanceTextView = (TextView) view.findViewById(R.id.distanceTextView);
    ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
    LatLng location = Utils.getLocation(getActivity());
    String distance = Utils.formatDistanceBetween(location, mAttraction.location);
    if (TextUtils.isEmpty(distance)) {
        distanceTextView.setVisibility(View.GONE);
    }
    nameTextView.setText(attractionName);
    distanceTextView.setText(distance);
    descTextView.setText(mAttraction.longDescription);
    int imageSize = getResources().getDimensionPixelSize(R.dimen.image_size) * Constants.IMAGE_ANIM_MULTIPLIER;
    Glide.with(getActivity()).load(mAttraction.imageUrl).diskCacheStrategy(DiskCacheStrategy.SOURCE).placeholder(R.color.lighter_gray).override(imageSize, imageSize).into(imageView);
    return view;
}

70. MapsActivity#drawPath()

View license
public void drawPath() {
    tripView.update(this, trip);
    GeospatialPoint firstPoint = trip.path.points.get(0);
    PolylineOptions options = new PolylineOptions().add(new LatLng(firstPoint.latDegrees, firstPoint.longDegrees)).width(10).color(Color.BLUE).geodesic(true).clickable(true);
    mMap.addMarker(new MarkerOptions().position(new LatLng(firstPoint.latDegrees, firstPoint.longDegrees)).title("Trip starts"));
    LatLng latLng = new LatLng(firstPoint.latDegrees, firstPoint.longDegrees);
    for (GeospatialPoint point : trip.path.points) {
        latLng = new LatLng(point.latDegrees, point.longDegrees);
        mMap.addCircle(new CircleOptions().center(latLng).radius(20).strokeColor(Color.RED).fillColor(Color.RED));
        options.add(latLng);
    }
    mMap.addPolyline(options);
    mMap.addMarker(new MarkerOptions().position(latLng).title("Trip ends"));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
}

71. NearByPatientsActivity#setUpMap()

View license
private void setUpMap() {
    AppLog.enter(TAG, AppLog.getMethodName());
    Vehicle currentVehicle = FordDemoUtil.getInstance().getVehicle();
    double srclat = 0.0;
    double srclng = 0.0;
    try {
        srclat = Double.parseDouble(currentVehicle.getLatitude());
        srclng = Double.parseDouble(currentVehicle.getLongitude());
    } catch (NumberFormatException ex) {
        AppLog.error(TAG, "Error : " + ex.toString());
        return;
    }
    LatLng origin = new LatLng(srclat, srclng);
    mCurrentVehicleMarker = mGoogleMap.addMarker(new MarkerOptions().position(origin).icon(BitmapDescriptorFactory.fromResource(R.drawable.current_vehicle)));
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(origin, 15));
    moveCarLocation();
    mNearByPatientsRetriverTask = new NearByPatientsRetriverTask(this);
    mNearByPatientsRetriverTask.execute();
    AppLog.exit(TAG, AppLog.getMethodName());
}

72. SwipeableCardAdapter#setMapLocation()

View license
public void setMapLocation(double lat, double lon, OptionView mOptionView) {
    mMapLocation = new LatLng(lat, lon);
    if (mGoogleMap != null) {
        updateMapContents(mOptionView);
    }
}

73. PolyUtilTest#copyList()

View license
/**
     * Returns a copy of the LatLng objects contained in one list to another list.  LatLng.latitude
     * and LatLng.longitude are immutable, so having references to the same LatLng object is
     * sufficient to guarantee that the contents are the same.
     * @param original original list
     * @return a copy of the original list, containing references to the same LatLng elements in
     * the same order.
     */
private List<LatLng> copyList(List<LatLng> original) {
    ArrayList<LatLng> copy = new ArrayList<>(original.size());
    for (LatLng l : original) {
        copy.add(l);
    }
    return copy;
}

74. MapsActivity#onMapReady()

Project: osmdroid
Source File: MapsActivity.java
View license
/**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

75. MapWrapper#setCenter()

Project: osmdroid
Source File: MapWrapper.java
View license
@Override
public void setCenter(final double aLatitude, final double aLongitude) {
    final LatLng latLng = new LatLng(aLatitude, aLongitude);
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}

76. MapWrapper#setPosition()

Project: osmdroid
Source File: MapWrapper.java
View license
@Override
public void setPosition(final IPosition aPosition) {
    final CameraPosition position = mGoogleMap.getCameraPosition();
    final LatLng latLng = new LatLng(aPosition.getLatitude(), aPosition.getLongitude());
    final float bearing = aPosition.hasBearing() ? aPosition.getBearing() : position.bearing;
    final float zoom = aPosition.hasZoomLevel() ? aPosition.getZoomLevel() : position.zoom;
    final CameraPosition newPosition = new CameraPosition(latLng, zoom, position.tilt, bearing);
    final CameraUpdate update = CameraUpdateFactory.newCameraPosition(newPosition);
    mGoogleMap.moveCamera(update);
}

77. Projection#toPixels()

Project: osmdroid
Source File: Projection.java
View license
@Override
public Point toPixels(final IGeoPoint in, final Point out) {
    final LatLng latLng = new LatLng(in.getLatitude(), in.getLongitude());
    final Point point = mProjection.toScreenLocation(latLng);
    if (out != null) {
        out.x = point.x;
        out.y = point.y;
    }
    return point;
}

78. Projection#fromPixels()

Project: osmdroid
Source File: Projection.java
View license
@Override
public IGeoPoint fromPixels(final int x, final int y) {
    mPoint.x = x;
    mPoint.y = y;
    final LatLng latLng = mProjection.fromScreenLocation(mPoint);
    return new GeoPoint(latLng);
}

79. PolyUtilTest#assertSimplifiedPointsFromLine()

View license
/**
     * Asserts that the simplified line is composed of points from the original line.
     * @param line original line
     * @param simplifiedLine simplified line
     */
private void assertSimplifiedPointsFromLine(List<LatLng> line, List<LatLng> simplifiedLine) {
    for (LatLng l : simplifiedLine) {
        assertTrue(line.contains(l));
    }
}

80. RecommendedRouteFragment#showCurrentLocationInMap()

View license
private void showCurrentLocationInMap() {
    Location currentLocation = getCurrentLocationArg();
    LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
    googleMap.addMarker(new MarkerOptions().position(latLng).title(getString(R.string.current_location)).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_location)));
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13f));
}

81. SplitStreetViewPanoramaAndMapDemoActivity#onCreate()

View license
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.split_street_view_panorama_and_map_demo);
    final LatLng markerPosition;
    if (savedInstanceState == null) {
        markerPosition = SYDNEY;
    } else {
        markerPosition = savedInstanceState.getParcelable(MARKER_POSITION_KEY);
    }
    SupportStreetViewPanoramaFragment streetViewPanoramaFragment = (SupportStreetViewPanoramaFragment) getSupportFragmentManager().findFragmentById(R.id.streetviewpanorama);
    streetViewPanoramaFragment.getStreetViewPanoramaAsync(new OnStreetViewPanoramaReadyCallback() {

        @Override
        public void onStreetViewPanoramaReady(StreetViewPanorama panorama) {
            mStreetViewPanorama = panorama;
            mStreetViewPanorama.setOnStreetViewPanoramaChangeListener(SplitStreetViewPanoramaAndMapDemoActivity.this);
            // its state.
            if (savedInstanceState == null) {
                mStreetViewPanorama.setPosition(SYDNEY);
            }
        }
    });
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(new OnMapReadyCallback() {

        @Override
        public void onMapReady(GoogleMap map) {
            map.setOnMarkerDragListener(SplitStreetViewPanoramaAndMapDemoActivity.this);
            // Creates a draggable marker. Long press to drag.
            mMarker = map.addMarker(new MarkerOptions().position(markerPosition).icon(BitmapDescriptorFactory.fromResource(R.drawable.pegman)).draggable(true));
        }
    });
}

82. SwipeableCard#setMapLocation()

Project: SwipeableCard
Source File: SwipeableCard.java
View license
/**
     * Set map location, check if Google Maps is not null, than update contents (Single marker)
     * @param lat latitude double
     * @param lon longitude double
     */
public void setMapLocation(double lat, double lon) {
    mMapLocation = new LatLng(lat, lon);
    if (mGoogleMap != null) {
        updateMapContents();
    }
}