com.google.maps.android.SphericalUtil Java Examples

The following examples show how to use com.google.maps.android.SphericalUtil. 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: AttractionListFragment.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
private static List<Attraction> loadAttractionsFromLocation(final LatLng curLatLng) {
    String closestCity = TouristAttractions.getClosestCity(curLatLng);
    if (closestCity != null) {
        List<Attraction> attractions = ATTRACTIONS.get(closestCity);
        if (curLatLng != null) {
            Collections.sort(attractions,
                    new Comparator<Attraction>() {
                        @Override
                        public int compare(Attraction lhs, Attraction rhs) {
                            double lhsDistance = SphericalUtil.computeDistanceBetween(
                                    lhs.location, curLatLng);
                            double rhsDistance = SphericalUtil.computeDistanceBetween(
                                    rhs.location, curLatLng);
                            return (int) (lhsDistance - rhsDistance);
                        }
                    }
            );
        }
        return attractions;
    }
    return null;
}
 
Example #2
Source File: TouristAttractions.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
public static String getClosestCity(LatLng curLatLng) {
    if (curLatLng == null) {
        // If location is unknown return test city so some data is shown
        return TEST_CITY;
    }

    double minDistance = 0;
    String closestCity = null;
    for (Map.Entry<String, LatLng> entry: CITY_LOCATIONS.entrySet()) {
        double distance = SphericalUtil.computeDistanceBetween(curLatLng, entry.getValue());
        if (minDistance == 0 || distance < minDistance) {
            minDistance = distance;
            closestCity = entry.getKey();
        }
    }
    return closestCity;
}
 
Example #3
Source File: TouristAttractions.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
public static String getClosestCity(LatLng curLatLng) {
    if (curLatLng == null) {
        // In debug build still return a city so some data is displayed
        if (BuildConfig.DEBUG) {
            return TEST_CITY;
        }
        return null;
    }

    double minDistance = 0;
    String closestCity = null;
    for (Map.Entry<String, LatLng> entry: CITY_LOCATIONS.entrySet()) {
        double distance = SphericalUtil.computeDistanceBetween(curLatLng, entry.getValue());
        if (minDistance == 0 || distance < minDistance) {
            minDistance = distance;
            closestCity = entry.getKey();
        }
    }
    return closestCity;
}
 
Example #4
Source File: AttractionListFragment.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
private static List<Attraction> loadAttractionsFromLocation(final LatLng curLatLng) {
    String closestCity = TouristAttractions.getClosestCity(curLatLng);
    if (closestCity != null) {
        List<Attraction> attractions = ATTRACTIONS.get(closestCity);
        if (curLatLng != null) {
            Collections.sort(attractions,
                    new Comparator<Attraction>() {
                        @Override
                        public int compare(Attraction lhs, Attraction rhs) {
                            double lhsDistance = SphericalUtil.computeDistanceBetween(
                                    lhs.location, curLatLng);
                            double rhsDistance = SphericalUtil.computeDistanceBetween(
                                    rhs.location, curLatLng);
                            return (int) (lhsDistance - rhsDistance);
                        }
                    }
            );
        }
        return attractions;
    }
    return null;
}
 
Example #5
Source File: Utils.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate distance between two LatLng points and format it nicely for
 * display. As this is a sample, it only statically supports metric units.
 * A production app should check locale and support the correct units.
 */
public static String formatDistanceBetween(LatLng point1, LatLng point2) {
    if (point1 == null || point2 == null) {
        return null;
    }

    NumberFormat numberFormat = NumberFormat.getNumberInstance();
    double distance = Math.round(SphericalUtil.computeDistanceBetween(point1, point2));

    // Adjust to KM if M goes over 1000 (see javadoc of method for note
    // on only supporting metric)
    if (distance >= 1000) {
        numberFormat.setMaximumFractionDigits(1);
        return numberFormat.format(distance / 1000) + DISTANCE_KM_POSTFIX;
    }
    return numberFormat.format(distance) + DISTANCE_M_POSTFIX;
}
 
Example #6
Source File: FeatureOverlayQuery.java    From geopackage-android-map with MIT License 6 votes vote down vote up
/**
 * Build a bounding box using the location coordinate click location and map view bounds
 *
 * @param latLng    click location
 * @param mapBounds map bounds
 * @return bounding box
 * @since 1.2.7
 */
public BoundingBox buildClickBoundingBox(LatLng latLng, BoundingBox mapBounds) {

    // Get the screen width and height a click occurs from a feature
    double width = TileBoundingBoxMapUtils.getLongitudeDistance(mapBounds) * screenClickPercentage;
    double height = TileBoundingBoxMapUtils.getLatitudeDistance(mapBounds) * screenClickPercentage;

    LatLng leftCoordinate = SphericalUtil.computeOffset(latLng, width, 270);
    LatLng upCoordinate = SphericalUtil.computeOffset(latLng, height, 0);
    LatLng rightCoordinate = SphericalUtil.computeOffset(latLng, width, 90);
    LatLng downCoordinate = SphericalUtil.computeOffset(latLng, height, 180);

    BoundingBox boundingBox = new BoundingBox(leftCoordinate.longitude, downCoordinate.latitude, rightCoordinate.longitude, upCoordinate.latitude);

    return boundingBox;
}
 
Example #7
Source File: TileBoundingBoxMapUtils.java    From geopackage-android-map with MIT License 6 votes vote down vote up
/**
 * Get the longitude distance in the middle latitude
 *
 * @param minLongitude min longitude
 * @param maxLongitude max longitude
 * @param latitude     latitude
 * @return distance
 * @since 1.2.7
 */
public static double getLongitudeDistance(double minLongitude,
                                          double maxLongitude,
                                          double latitude) {
    LatLng leftMiddle = new LatLng(latitude, minLongitude);
    LatLng middle = new LatLng(latitude, (minLongitude + maxLongitude) / 2.0);
    LatLng rightMiddle = new LatLng(latitude, maxLongitude);

    List<LatLng> path = new ArrayList<LatLng>();
    path.add(leftMiddle);
    path.add(middle);
    path.add(rightMiddle);

    double lonDistance = SphericalUtil.computeLength(path);
    return lonDistance;
}
 
Example #8
Source File: TouristAttractions.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
public static String getClosestCity(LatLng curLatLng) {
    if (curLatLng == null) {
        // In debug build still return a city so some data is displayed
        if (BuildConfig.DEBUG) {
            return TEST_CITY;
        }
        return null;
    }

    double minDistance = 0;
    String closestCity = null;
    for (Map.Entry<String, LatLng> entry: CITY_LOCATIONS.entrySet()) {
        double distance = SphericalUtil.computeDistanceBetween(curLatLng, entry.getValue());
        if (minDistance == 0 || distance < minDistance) {
            minDistance = distance;
            closestCity = entry.getKey();
        }
    }
    return closestCity;
}
 
Example #9
Source File: Utils.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate distance between two LatLng points and format it nicely for
 * display. As this is a sample, it only statically supports metric units.
 * A production app should check locale and support the correct units.
 */
public static String formatDistanceBetween(LatLng point1, LatLng point2) {
    if (point1 == null || point2 == null) {
        return null;
    }

    NumberFormat numberFormat = NumberFormat.getNumberInstance();
    double distance = Math.round(SphericalUtil.computeDistanceBetween(point1, point2));

    // Adjust to KM if M goes over 1000 (see javadoc of method for note
    // on only supporting metric)
    if (distance >= 1000) {
        numberFormat.setMaximumFractionDigits(1);
        return numberFormat.format(distance / 1000) + DISTANCE_KM_POSTFIX;
    }
    return numberFormat.format(distance) + DISTANCE_M_POSTFIX;
}
 
Example #10
Source File: AttractionListFragment.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
private static List<Attraction> loadAttractionsFromLocation(final LatLng curLatLng) {
    String closestCity = TouristAttractions.getClosestCity(curLatLng);
    if (closestCity != null) {
        List<Attraction> attractions = ATTRACTIONS.get(closestCity);
        if (curLatLng != null) {
            Collections.sort(attractions,
                    new Comparator<Attraction>() {
                        @Override
                        public int compare(Attraction lhs, Attraction rhs) {
                            double lhsDistance = SphericalUtil.computeDistanceBetween(
                                    lhs.location, curLatLng);
                            double rhsDistance = SphericalUtil.computeDistanceBetween(
                                    rhs.location, curLatLng);
                            return (int) (lhsDistance - rhsDistance);
                        }
                    }
            );
        }
        return attractions;
    }
    return null;
}
 
Example #11
Source File: Utils.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate distance between two LatLng points and format it nicely for
 * display. As this is a sample, it only statically supports metric units.
 * A production app should check locale and support the correct units.
 */
public static String formatDistanceBetween(LatLng point1, LatLng point2) {
    if (point1 == null || point2 == null) {
        return null;
    }

    NumberFormat numberFormat = NumberFormat.getNumberInstance();
    double distance = Math.round(SphericalUtil.computeDistanceBetween(point1, point2));

    // Adjust to KM if M goes over 1000 (see javadoc of method for note
    // on only supporting metric)
    if (distance >= 1000) {
        numberFormat.setMaximumFractionDigits(1);
        return numberFormat.format(distance / 1000) + DISTANCE_KM_POSTFIX;
    }
    return numberFormat.format(distance) + DISTANCE_M_POSTFIX;
}
 
Example #12
Source File: RichLayer.java    From richmaps with Apache License 2.0 5 votes vote down vote up
public void refresh() {
    CameraPosition cameraPosition = map.getCameraPosition();
    if (cameraPosition.zoom >= MINIMUM_ZOOM_LEVEL) {
        Projection projection = map.getProjection();

        prepareBitmap();
        draw(bitmap, projection);

        float mapWidth = (float) SphericalUtil.computeDistanceBetween(
                projection.getVisibleRegion().nearLeft,
                projection.getVisibleRegion().nearRight);

        if (overlay == null) {
            GroundOverlayOptions background = new GroundOverlayOptions()
                    .image(BitmapDescriptorFactory.fromBitmap(bitmap))
                    .position(cameraPosition.target, mapWidth)
                    .bearing(cameraPosition.bearing)
                    .zIndex(zIndex);
            overlay = map.addGroundOverlay(background);
        } else {
            overlay.setImage(BitmapDescriptorFactory.fromBitmap(bitmap));
            overlay.setPosition(cameraPosition.target);
            overlay.setDimensions(mapWidth);
            overlay.setBearing(cameraPosition.bearing);
        }
    } else {
        if (overlay != null) {
            overlay.remove();
            overlay = null;
        }
    }
}
 
Example #13
Source File: HeatmapsPlacesDemoActivity.java    From android-maps-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Makes four radar search requests for the given keyword, then parses the
 * json output and returns the search results as a collection of LatLng objects.
 *
 * @param keyword A string to use as a search term for the radar search
 * @return Returns the search results from radar search as a collection
 * of LatLng objects.
 */
private Collection<LatLng> getPoints(String keyword) {
    HashMap<String, LatLng> results = new HashMap<>();

    // Calculate four equidistant points around Sydney to use as search centers
    //   so that four searches can be done.
    ArrayList<LatLng> searchCenters = new ArrayList<>(4);
    for (int heading = 45; heading < 360; heading += 90) {
        searchCenters.add(SphericalUtil.computeOffset(SYDNEY, SEARCH_RADIUS / 2, heading));
    }

    for (int j = 0; j < 4; j++) {
        String jsonResults = getJsonPlaces(keyword, searchCenters.get(j));
        try {
            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults);
            JSONArray pointsJsonArray = jsonObj.getJSONArray("results");

            // Extract the Place descriptions from the results
            for (int i = 0; i < pointsJsonArray.length(); i++) {
                if (!results.containsKey(pointsJsonArray.getJSONObject(i).getString("id"))) {
                    JSONObject location = pointsJsonArray.getJSONObject(i)
                            .getJSONObject("geometry").getJSONObject("location");
                    results.put(pointsJsonArray.getJSONObject(i).getString("id"),
                            new LatLng(location.getDouble("lat"),
                                    location.getDouble("lng")));
                }
            }
        } catch (JSONException e) {
            Toast.makeText(this, "Cannot process JSON results", Toast.LENGTH_SHORT).show();
        }
    }
    return results.values();
}
 
Example #14
Source File: SphericalGeometryActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void showDistance() {
    double distance = SphericalUtil.computeDistanceBetween( mMarker1.getPosition(), mMarker2.getPosition() );
    if( distance < 1000 ) {
        Toast.makeText(this, String.format( "%4.2f%s", distance, "m" ), Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, String.format("%4.3f%s", distance/1000, "km"), Toast.LENGTH_LONG).show();
    }
}
 
Example #15
Source File: Map.java    From MapsMeasure with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new point, calculates the new distance and draws the point and a
 * line to it
 *
 * @param p the new point
 */
void addPoint(final LatLng p) {
    if (!trace.isEmpty()) {
        lines.push(mMap.addPolyline(
                new PolylineOptions().color(COLOR_LINE).width(LINE_WIDTH).add(trace.peek())
                        .add(p)));
        distance += SphericalUtil.computeDistanceBetween(p, trace.peek());
    }
    points.push(drawMarker(p));
    trace.push(p);
    updateValueText();
}
 
Example #16
Source File: MockBackgroundLocationService.java    From android-location-service with Apache License 2.0 5 votes vote down vote up
@Override public void handleMessage(Message msg) {
    if (!mTestStarted) {
        mTestStarted = true;
        long elapsedTimeNanos;
        long currentTime;
        LatLng[] mockLocations = (LatLng[]) msg.obj;
        if (mockLocations != null && mockLocations.length > 0) {
            Location mockLocation = new Location("fused");
            LatLng lastLocation = null;
            for (LatLng latLng : mockLocations) {
                if (getGoogleApiClient() == null || !getGoogleApiClient().isConnected()) {
                    break;
                }
                currentTime = System.currentTimeMillis();
                if (Build.VERSION.SDK_INT >= 17) {
                    elapsedTimeNanos = SystemClock.elapsedRealtimeNanos();
                    mockLocation.setElapsedRealtimeNanos(elapsedTimeNanos);
                }
                mockLocation.setTime(currentTime);
                mockLocation.setAccuracy(mAccuracy);
                mockLocation.setLatitude(latLng.latitude);
                mockLocation.setLongitude(latLng.longitude);
                if (lastLocation != null) {
                    mockLocation.setBearing((float) SphericalUtil.computeHeading(lastLocation, latLng));
                }
                lastLocation = latLng;
                LocationServices.FusedLocationApi.setMockLocation(getGoogleApiClient(), mockLocation);

                // wait the specified interval
                try {
                    Thread.sleep(mSendInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }
        mTestStarted = false;
    }
}
 
Example #17
Source File: TileBoundingBoxMapUtils.java    From geopackage-android-map with MIT License 5 votes vote down vote up
/**
 * Get the latitude distance
 *
 * @param minLatitude min latitude
 * @param maxLatitude max latitude
 * @return distance
 */
public static double getLatitudeDistance(double minLatitude,
                                         double maxLatitude) {
    LatLng lowerMiddle = new LatLng(minLatitude, 0);
    LatLng upperMiddle = new LatLng(maxLatitude, 0);
    double latDistance = SphericalUtil.computeDistanceBetween(lowerMiddle,
            upperMiddle);
    return latDistance;
}
 
Example #18
Source File: GoogleMapShapeMarkers.java    From geopackage-android-map with MIT License 5 votes vote down vote up
/**
 * Polygon add a marker in the list of markers to where it is closest to the
 * the surrounding points
 *
 * @param marker  marker
 * @param markers list of markers
 */
public static void addMarkerAsPolygon(Marker marker, List<Marker> markers) {
    LatLng position = marker.getPosition();
    int insertLocation = markers.size();
    if (markers.size() > 2) {
        double[] distances = new double[markers.size()];
        insertLocation = 0;
        distances[0] = SphericalUtil.computeDistanceBetween(position,
                markers.get(0).getPosition());
        for (int i = 1; i < markers.size(); i++) {
            distances[i] = SphericalUtil.computeDistanceBetween(position,
                    markers.get(i).getPosition());
            if (distances[i] < distances[insertLocation]) {
                insertLocation = i;
            }
        }

        int beforeLocation = insertLocation > 0 ? insertLocation - 1
                : distances.length - 1;
        int afterLocation = insertLocation < distances.length - 1 ? insertLocation + 1
                : 0;

        if (distances[beforeLocation] > distances[afterLocation]) {
            insertLocation = afterLocation;
        }

    }
    markers.add(insertLocation, marker);
}
 
Example #19
Source File: GoogleMapShapeMarkers.java    From geopackage-android-map with MIT License 4 votes vote down vote up
/**
 * Polyline add a marker in the list of markers to where it is closest to
 * the the surrounding points
 *
 * @param marker  marker
 * @param markers list of markers
 */
public static void addMarkerAsPolyline(Marker marker, List<Marker> markers) {
    LatLng position = marker.getPosition();
    int insertLocation = markers.size();
    if (markers.size() > 1) {
        double[] distances = new double[markers.size()];
        insertLocation = 0;
        distances[0] = SphericalUtil.computeDistanceBetween(position,
                markers.get(0).getPosition());
        for (int i = 1; i < markers.size(); i++) {
            distances[i] = SphericalUtil.computeDistanceBetween(position,
                    markers.get(i).getPosition());
            if (distances[i] < distances[insertLocation]) {
                insertLocation = i;
            }
        }

        Integer beforeLocation = insertLocation > 0 ? insertLocation - 1
                : null;
        Integer afterLocation = insertLocation < distances.length - 1 ? insertLocation + 1
                : null;

        if (beforeLocation != null && afterLocation != null) {
            if (distances[beforeLocation] > distances[afterLocation]) {
                insertLocation = afterLocation;
            }
        } else if (beforeLocation != null) {
            if (distances[beforeLocation] >= SphericalUtil
                    .computeDistanceBetween(markers.get(beforeLocation)
                            .getPosition(), markers.get(insertLocation)
                            .getPosition())) {
                insertLocation++;
            }
        } else {
            if (distances[afterLocation] < SphericalUtil
                    .computeDistanceBetween(markers.get(afterLocation)
                            .getPosition(), markers.get(insertLocation)
                            .getPosition())) {
                insertLocation++;
            }
        }

    }
    markers.add(insertLocation, marker);
}
 
Example #20
Source File: SphericalGeometryActivity.java    From AndroidDemoProjects with Apache License 2.0 4 votes vote down vote up
private void showHeading() {
    double heading = SphericalUtil.computeHeading( mMarker1.getPosition(), mMarker2.getPosition() );
    Toast.makeText( this, "Heading: " + heading, Toast.LENGTH_LONG ).show();
}
 
Example #21
Source File: DistanceDemoActivity.java    From android-maps-utils with Apache License 2.0 4 votes vote down vote up
private void showDistance() {
    double distance = SphericalUtil.computeDistanceBetween(mMarkerA.getPosition(), mMarkerB.getPosition());
    mTextView.setText("The markers are " + formatNumber(distance) + " apart.");
}
 
Example #22
Source File: MapUtils.java    From geopackage-android-map with MIT License 3 votes vote down vote up
/**
 * Get the allowable tolerance distance in meters from the click location on the map view and map with the screen percentage tolerance.
 *
 * @param latLng                click location
 * @param view                  map view
 * @param map                   map
 * @param screenClickPercentage screen click percentage between 0.0 and 1.0 for how close a feature
 *                              on the screen must be to be included in a click query
 * @return tolerance distance in meters
 */
public static double getToleranceDistance(LatLng latLng, View view, GoogleMap map, float screenClickPercentage) {

    LatLngBoundingBox latLngBoundingBox = buildClickLatLngBoundingBox(latLng, view, map, screenClickPercentage);

    double longitudeDistance = SphericalUtil.computeDistanceBetween(latLngBoundingBox.getLeftCoordinate(), latLngBoundingBox.getRightCoordinate());
    double latitudeDistance = SphericalUtil.computeDistanceBetween(latLngBoundingBox.getDownCoordinate(), latLngBoundingBox.getUpCoordinate());

    double distance = Math.max(longitudeDistance, latitudeDistance);

    return distance;
}
 
Example #23
Source File: CheckInActivity.java    From StudentAttendanceCheck with MIT License 3 votes vote down vote up
public LatLngBounds toBounds(LatLng center, double radius) {

        LatLng southwest = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 225);
        LatLng northeast = SphericalUtil.computeOffset(center, radius * Math.sqrt(2.0), 45);

        Log.w("southwest", String.valueOf(southwest));
        Log.w("northeast", String.valueOf(northeast));

        // return the boundary
        return new LatLngBounds(southwest, northeast);

    }
 
Example #24
Source File: GoogleMapShapeConverter.java    From geopackage-android-map with MIT License 2 votes vote down vote up
/**
 * Determine the closed points orientation
 *
 * @param points closed points
 * @return orientation
 * @since 1.3.2
 */
public PolygonOrientation getOrientation(List<LatLng> points) {
    return SphericalUtil.computeSignedArea(points) >= 0 ? PolygonOrientation.COUNTERCLOCKWISE : PolygonOrientation.CLOCKWISE;
}
 
Example #25
Source File: MapUtils.java    From geopackage-android-map with MIT License 2 votes vote down vote up
/**
 * Is the point near the shape point
 *
 * @param point      point
 * @param shapePoint shape point
 * @param tolerance  distance tolerance
 * @return true if near
 */
public static boolean isPointNearPoint(LatLng point, LatLng shapePoint, double tolerance) {
    return SphericalUtil.computeDistanceBetween(point, shapePoint) <= tolerance;
}