下面列出了怎么用com.google.android.gms.maps.model.LatLng的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
/**
* Sets marker at given location on map
*
* @param LocationLat latitude
* @param LocationLong longitude
* @param LocationName name of location
* @param LocationIcon icon
*/
public void ShowMarker(Double LocationLat, Double LocationLong, String LocationName, Integer LocationIcon) {
LatLng Coord = new LatLng(LocationLat, LocationLong);
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (map != null) {
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(Coord, 10));
MarkerOptions abc = new MarkerOptions();
MarkerOptions x = abc
.title(LocationName)
.position(Coord)
.icon(BitmapDescriptorFactory.fromResource(LocationIcon));
map.addMarker(x);
}
}
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent != null ? intent.getAction() : null;
if (ACTION_ADD_GEOFENCES.equals(action)) {
addGeofencesInternal();
} else if (ACTION_GEOFENCE_TRIGGERED.equals(action)) {
geofenceTriggered(intent);
} else if (ACTION_REQUEST_LOCATION.equals(action)) {
requestLocationInternal();
} else if (ACTION_LOCATION_UPDATED.equals(action)) {
locationUpdated(intent);
} else if (ACTION_CLEAR_NOTIFICATION.equals(action)) {
clearNotificationInternal();
} else if (ACTION_CLEAR_REMOTE_NOTIFICATIONS.equals(action)) {
clearRemoteNotifications();
} else if (ACTION_FAKE_UPDATE.equals(action)) {
LatLng currentLocation = Utils.getLocation(this);
// If location unknown use test city, otherwise use closest city
String city = currentLocation == null ? TouristAttractions.TEST_CITY :
TouristAttractions.getClosestCity(currentLocation);
showNotification(city,
intent.getBooleanExtra(EXTRA_TEST_MICROAPP, Constants.USE_MICRO_APP));
}
}
public void initialize(boolean showPolyLine) {
reset();
this.showPolyline = showPolyLine;
highLightMarker(0);
if (showPolyLine) {
polyLine = initializePolyLine();
}
// We first need to put the camera in the correct position for the first run (we need 2 markers for this).....
LatLng markerPos = markers.get(0).getPosition();
LatLng secondPos = markers.get(1).getPosition();
setupCameraPositionForMovement(markerPos, secondPos);
}
private int whichMapQ(double lat, double lon) {
LatLng center = mMap.getCameraPosition().target;
double mapCenterLat = center.latitude;
double mapCenterLon = center.longitude;
if( (lat < mapCenterLat) && (lon < mapCenterLon)) {
return 1;
} else if( (lat > mapCenterLat) && (lon < mapCenterLon)) {
return 2;
} else if( (lat > mapCenterLat) && (lon > mapCenterLon)) {
return 3;
} else if( (lat < mapCenterLat) && (lon > mapCenterLon)) {
return 4;
} else {
return 0;
}
}
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;
}
public Marker addPointMarkerByHistory(MapPointLatLng mpl) {
BitmapDescriptor mBitmapDescriptor;
float anchorY;
if (this.lineMarkerSelectListener.getOration() != 0) {
mBitmapDescriptor = this.gdCustemMarkerView.createMapPointAngleNoPioView(this.context, R.drawable.x8_ai_line_point_with_angle1, mpl.altitude, mpl.nPos, mpl.showAngle, mpl.isSelect, false);
anchorY = 0.64285713f;
} else if (mpl.mInrertestPoint != null) {
mpl.setAngle(getPointAngle(mpl, mpl.mInrertestPoint));
mBitmapDescriptor = this.gdCustemMarkerView.createMapPointAngleNoPioView(this.context, R.drawable.x8_ai_line_point_with_angle1, mpl.altitude, mpl.nPos, mpl.showAngle, mpl.isSelect, false);
anchorY = 0.64285713f;
} else {
mBitmapDescriptor = this.gdCustemMarkerView.createMapPointNoAngleNoPioView(this.context, R.drawable.x8_ai_line_point_no_angle1, mpl.altitude, mpl.nPos, mpl.isSelect, false);
anchorY = 0.64285713f;
}
Marker marker = this.googleMap.addMarker(new MarkerOptions().position(new LatLng(mpl.latitude, mpl.longitude)).icon(mBitmapDescriptor).anchor(0.5f, anchorY).draggable(false));
marker.setFlat(true);
return marker;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
String lat= getIntent().getStringExtra("lat");
String longg= getIntent().getStringExtra("long");
latitude= Double.parseDouble(lat);
longitude= Double.parseDouble(longg);
kochi = new LatLng(latitude, longitude);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
private void drawOverlay( LatLng location, int width, int height ) {
GroundOverlayOptions options = new GroundOverlayOptions();
options.position(location, width, height);
options.image( BitmapDescriptorFactory
.fromBitmap( BitmapFactory
.decodeResource( getResources(), R.mipmap.ic_launcher ) ) );
getMap().addGroundOverlay(options);
}
@Override public void onMapClick(LatLng latLng) {
if (latLng != null) {
appendLog(
"Map onMapClick triggered with lat: " + latLng.latitude + ", lng: "
+ latLng.longitude);
map.getMapInterface().getScreenLocation(latLng, this);
} else {
appendLog("Map onMapClick triggered with null latLng");
}
}
@Override
protected Address doInBackground(LatLng... latLngs) {
if (latLngs.length == 0) return null;
LatLng latLng = latLngs[0];
if (latLng == null) return null;
try {
List<Address> result = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
return !result.isEmpty() ? result.get(0) : null;
} catch (IOException e) {
Log.w(TAG, "Failed to get address from location", e);
return null;
}
}
@Before
public void alloc() {
mTitle = "Title";
mDescription = "Description";
mGalleryId = "galleryId";
mPosition = new LatLng(51.5014, -0.1419);
mGalleryUnderTest = new Gallery(mTitle, mDescription, mGalleryId, mPosition);
}
public FimiPoint toScreenLocation(double lat, double lng) {
FimiPoint p = new FimiPoint();
Point mPoint = this.googleMap.getProjection().toScreenLocation(new LatLng(lat, lng));
if (mPoint != null) {
p.x = mPoint.x;
p.y = mPoint.y;
}
return p;
}
/**
* 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;
}
@Override
protected void onPostExecute(final Address address) {
if (address == null) {
if (BuildConfig.DEBUG) Logger.log("no location found");
Toast.makeText(map.getBaseContext(), R.string.no_location_found, Toast.LENGTH_SHORT).show();
} else {
map.getMap().animateCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(address.getLatitude(), address.getLongitude()),
Math.max(10, map.getMap().getCameraPosition().zoom)));
}
}
public double[] getManLatLng() {
double[] latLng = new double[2];
if (this.gglMapLocationManager == null) {
return null;
}
LatLng ll = this.gglMapLocationManager.getManLocation();
if (ll == null) {
return null;
}
latLng[0] = ll.latitude;
latLng[1] = ll.longitude;
return latLng;
}
/**
* Perform a query based upon the map click location and build a info message
*
* @param latLng location
* @param zoom current zoom level
* @param boundingBox click bounding box
* @param tolerance tolerance distance
* @param projection desired geometry projection
* @return information message on what was clicked, or null
*/
private String buildMapClickMessage(LatLng latLng, double zoom, BoundingBox boundingBox, double tolerance, Projection projection) {
String message = null;
// Verify the features are indexed and we are getting information
if (isIndexed() && (maxFeaturesInfo || featuresInfo)) {
if (isOnAtCurrentZoom(zoom, latLng)) {
// Get the number of features in the tile location
long tileFeatureCount = tileFeatureCount(latLng, zoom);
// If more than a configured max features to draw
if (isMoreThanMaxFeatures(tileFeatureCount)) {
// Build the max features message
if (maxFeaturesInfo) {
message = buildMaxFeaturesInfoMessage(tileFeatureCount);
}
}
// Else, query for the features near the click
else if (featuresInfo) {
// Query for results and build the message
FeatureIndexResults results = queryFeatures(boundingBox, projection);
message = featureInfoBuilder.buildResultsInfoMessageAndClose(results, tolerance, latLng, projection);
}
}
}
return message;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.map_list_menu_map:
if (googleMap != null) {
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
break;
case R.id.map_list_menu_satellite:
if (googleMap != null) {
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
break;
case R.id.map_list_menu_hybrid:
if (googleMap != null) {
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
break;
case R.id.map_to_my_location:
if (myLocation != null) {
LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
if (googleMap != null) {
CameraUpdate position = CameraUpdateFactory.newLatLngZoom(latLng, googleMap.getMaxZoomLevel() - 8);
googleMap.animateCamera(position);
}
}
break;
case android.R.id.home:
finishFragment();
break;
}
return true;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_select_location_manual , container , false);
context = getActivity();
latLng = new LatLng(0 , 0);
setupViews();
return v;
}
@Override
public void onLocationChanged(@NonNull Location location) {
mLocation = location;
if (!isAdded() || isDetached() || mMap == null)
return;
LatLng pos = new LatLng(location.getLatitude(), location.getLongitude());
if (mLine != null) {
ArrayList<LatLng> points = new ArrayList<>();
points.add(pos);
points.add(mKaabePos);
mLine.setPoints(points);
mMarker.setPosition(pos);
mCircle.setCenter(pos);
mCircle.setRadius(location.getAccuracy());
mMap.animateCamera(CameraUpdateFactory.newLatLng(pos));
} else {
//zoom first time
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15));
mLine = mMap.addPolyline(
new PolylineOptions().add(pos).add(mKaabePos).geodesic(true).color(Color.parseColor("#3bb2d0")).width(3).zIndex(1));
mMarker = mMap.addMarker(
new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mylocation)).anchor(0.5f, 0.5f).position(pos)
.zIndex(2));
mCircle = mMap.addCircle(
new CircleOptions().center(pos).fillColor(0xAA4FC3F7).strokeColor(getResources().getColor(R.color.colorPrimary)).strokeWidth(2)
.radius(mLocation.getAccuracy()));
}
}
public Geofence(Long id, boolean active, String name, LatLng centerLocation, double radius, Bitmap snapshot, Map<EventType, List<Action>> actionsMap, @State String state) {
this.id = id;
this.active = active;
this.name = name;
this.centerLocation = centerLocation;
this.radius = radius;
this.snapshot = snapshot;
this.actionsMap = actionsMap;
this.state = state;
}
@Override
public void onLocationChanged(@NonNull Location location) {
mLocation = location;
if (!isAdded() || isDetached() || mMap == null)
return;
LatLng pos = new LatLng(location.getLatitude(), location.getLongitude());
if (mLine != null) {
ArrayList<LatLng> points = new ArrayList<>();
points.add(pos);
points.add(mKaabePos);
mLine.setPoints(points);
mMarker.setPosition(pos);
mCircle.setCenter(pos);
mCircle.setRadius(location.getAccuracy());
mMap.animateCamera(CameraUpdateFactory.newLatLng(pos));
} else {
//zoom first time
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15));
mLine = mMap.addPolyline(
new PolylineOptions().add(pos).add(mKaabePos).geodesic(true).color(Color.parseColor("#3bb2d0")).width(3).zIndex(1));
mMarker = mMap.addMarker(
new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mylocation)).anchor(0.5f, 0.5f).position(pos)
.zIndex(2));
mCircle = mMap.addCircle(
new CircleOptions().center(pos).fillColor(0xAA4FC3F7).strokeColor(getResources().getColor(R.color.colorPrimary)).strokeWidth(2)
.radius(mLocation.getAccuracy()));
}
}
public void animateCamera(final LatLng latLng) {
if (googleMap != null) {
googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
latLng,
17
));
}
});
}
}
private void initCamera() {
CameraPosition position = CameraPosition.builder()
.target( new LatLng( 40.7506, -73.9936 ) )
.zoom( 18f )
.bearing( 0.0f )
.tilt( 0.0f )
.build();
getMap().animateCamera( CameraUpdateFactory.newCameraPosition( position ), null );
getMap().setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
@Override
public void onMapLongClick(LatLng latLng) {
MarkerOptions options = new MarkerOptions().position( latLng );
options.title( getAddressFromLatLng(latLng) );
options.icon( BitmapDescriptorFactory.fromBitmap(
BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher ) ) );
getMap().addMarker(options);
}
@Override
public void onMapReady( GoogleMap googleMap ){
map = googleMap;
if( isLocationEnable() ){
Location location = getLastKnownLocation();
if( location != null ){
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng current = new LatLng( latitude, longitude );
map.moveCamera( CameraUpdateFactory.newLatLngZoom( current, DEFAULT_ZOOM ) );
}
}
setupMap();
}
/**
* 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);
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {@link #mMap} is not null.
*/
private void setUpMap() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQ_LOCATION);
im.actor.runtime.Log.d("Permissions", "MapPickerActivity.setUpMap - no permission :c");
return;
}
}
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
for (String provider : locationManager.getAllProviders()) {
currentLocation = locationManager.getLastKnownLocation(provider);
if (currentLocation != null) {
break;
}
}
if (currentLocation != null) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), 14));
fetchPlaces(null);
}
mMap.setOnMyLocationChangeListener(this);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
mMap.getUiSettings().setCompassEnabled(false);
mMap.setMyLocationEnabled(true);
mMap.setOnMapLongClickListener(this);
mMap.setOnMarkerClickListener(this);
}
@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);
}