放大特定路线 google 地图

zoom over specific route google map

我有一个随机纬度和经度点的列表,我正在绘制它们之间的路线。我的问题是如何在 google 地图中绑定这条路线,我在下面的实用方法

public static void drawRouteIntoMap(final List<? extends MapHelper> position, final GoogleMap googleMap) {
    /*List<MapHelper> position = new ArrayList<MapHelper>();
    for (int i = lastPosition; i < maps.size(); i++) {
        position.add(maps.get(i));
    }*/
    if (position.size() > 0 && Validator.isNotNull(googleMap)) {
        googleMap.clear();
        List<PolylineOptions> polylineOptionses = new ArrayList<PolylineOptions>();
        PolylineOptions option = null;
        Boolean lastPause = null;
        for (MapHelper map : position) {
            if (map.isPause()) {
                if (Validator.isNull(lastPause) || !lastPause) {
                    option = new PolylineOptions().width(5).color(Color.rgb(255, 0, 155)).geodesic(true);
                    polylineOptionses.add(option);
                }
                option.add(new LatLng(map.getLatitude(), map.getLongitude()));
            } else {
                if (Validator.isNull(lastPause) || lastPause) {
                    option = new PolylineOptions().width(5).color(Color.rgb(0, 179, 253)).geodesic(true);
                    polylineOptionses.add(option);
                }
                option.add(new LatLng(map.getLatitude(), map.getLongitude()));
            }
            lastPause = map.isPause();
        }
        for (PolylineOptions options : polylineOptionses) {
            googleMap.addPolyline(options);
        }
        if(Validator.isNotNull(option)){
            //List<LatLng> points = option.getPoints();
            final LatLngBounds.Builder mapBounds = new LatLngBounds.Builder();

            googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
                @Override
                public void onMapLoaded() {
                    LatLng startPoint = new LatLng(position.get(0).getLatitude(), position.get(0).getLongitude());
                    googleMap.addMarker(new MarkerOptions().position(startPoint).title("start").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
                    mapBounds.include(startPoint);
                    LatLng endPoint = new LatLng(position.get(position.size() - 1).getLatitude(), position.get(position.size() - 1).getLongitude());
                    mapBounds.include(endPoint);
                    googleMap.addMarker(new MarkerOptions().position(endPoint).title("finish").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
                    googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 10));
                   /* googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 10));
                    googleMap.moveCamera(CameraUpdateFactory.zoomOut());*/

                }
            });
        }

    }
}

这里last pause是boolean,表示是否为红色折线的暂停点

但它不是working.Any感谢帮助。

 googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(endPoint,zoomLevel));

如果对你有帮助就试试吧

放大不起作用的原因可能是因为在调用该方法时地图尚未膨胀:

moveCamera(com.google.android.gms.maps.CameraUpdate)

尝试将 ViewTreeObserver.OnGlobalLayoutListener 添加到地图:

ViewTreeObserver vto = googleMap.getViewTreeObserver();
ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            googleMap.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        } else {
            googleMap.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 10));
    }
};
vto.addOnGlobalLayoutListener(globalLayoutListener);

如果上述方法不起作用 GoogleMap 有自己的布局侦听器,您可以使用它:

googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {

    @Override
    public void onCameraChange(CameraPosition arg0) {
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 10));
        googleMap.setOnCameraChangeListener(null);
    }
});

但是,从 API 的 play-services-maps 9.4.0 版本开始,上述方法已弃用。使用以下之一:

试试这样实现

/**
 * Zooms a Route (given a List of LalLng) at the greatest possible zoom level.
 *
 * @param googleMap: instance of GoogleMap
 * @param lstLatLngRoute: list of LatLng forming Route
 */
public void zoomRoute(GoogleMap googleMap, List<LatLng> lstLatLngRoute) {

    if (googleMap == null || lstLatLngRoute == null || lstLatLngRoute.isEmpty()) return;

    LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
    for (LatLng latLngPoint : lstLatLngRoute)
        boundsBuilder.include(latLngPoint);

    int routePadding = 100;
    LatLngBounds latLngBounds = boundsBuilder.build();

    googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, routePadding));
}

更新

看了图片,上面有布局图。所以它需要你设置 Variable Padding。你可以这样做

googleMap.setPadding(left, top, right, bottom);

注意:设置变量padding时,可以初始化routePadding = 0; 在您的情况下,近似值是:left = right = 10bottom=100top=200。设置后,您可以根据需要校准它们。

Recommendation: You can calculate the height of those (top and bottom) layouts in pixels and then set padding accordingly.

您需要将构成多段线的所有点包含到您的 mapBounds 对象中。

此外,您正在使用 animateCamera 更新相机,然后使用 moveCamera 移动它。第二个相机更新覆盖第一个。只需删除行

googleMap.moveCamera(CameraUpdateFactory.zoomOut());

这一行也是必要的(你不需要移动和动画相机,只是其中之一):

googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 10));

如果您需要缩小地图,您可以使用 CameraUpdateFactory.newLatLngBounds 方法的填充参数。

我实施了与@rishabh-dutt-sharma 类似的解决方案,但有一些曲折:

  • 首先,在缩放之前检查点是否已经在视图内。如果是,请不要更改它。这意味着用户 UI 中不需要的更改更少。
  • 其次,一种特殊情况是只有一个点。这在显示标记列表时很有用,在您的特定情况下可能不需要。这个有用的原因是因为在单点的情况下,缩放通常会增加到最大,通常这太多了。

这是代码(改编自我的原始代码,希望没有错别字):

    public void zoomRoute(GoogleMap googleMap, List<LatLng> lstLatLngRoute) {

        if (googleMap == null || lstLatLngRoute == null || lstLatLngRoute.isEmpty()) return;

        LatLngBounds currentLatLongBounds =
                googleMap.getProjection().getVisibleRegion().latLngBounds;
        boolean updateBounds = false;

        for (LatLng latLng : lstLatLngRoute) {
            if (!currentLatLongBounds.contains(latLng)) {
                updateBounds = true;
            }
        }

        if (updateBounds) {

            CameraUpdate cameraUpdate;

            if (lstLatLngRoute.size() == 1) {

                LatLng latLng = lstLatLngRoute.iterator().next();
                cameraUpdate = CameraUpdateFactory.newLatLng(latLng);

            } else {

                LatLngBounds.Builder builder = LatLngBounds.builder();
                for (LatLng latLng : lstLatLngRoute) {
                    builder.include(latLng);
                }
                LatLngBounds latLongBounds = builder.build();

                cameraUpdate =
                        CameraUpdateFactory.newLatLngBounds(latLongBounds, MAP_ZOOM_PADDING);

            }

            try {
                googleMap.animateCamera(cameraUpdate, MAP_CAMERA_ANIMATION_DURATION_IN_MILLIS,
                        new GoogleMap.CancelableCallback() {
                            @Override
                            public void onFinish() {
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            } catch (IllegalStateException ex) {
                // Ignore it. We're just being a bit lazy, as this exception only happens if
                // we try to animate the camera before the map has a size
            }
        }
    }

我是怎么做到的。

Android - plotting gps coordinate on custom map

是的,您可以绘制不在可见地图上的点。通过设置 LatLngBounds 来解决这个问题。然后显示 LatLngBounds 的地图。您还可以移动地图以显示 LatLngBounds。这里没有什么棘手的,没有地球的切线、斜坡或双曲率。所有这些都以度数为单位进行处理,所以不要过度考虑您的解决方案。如果您转动地图,点将随之转动。因此,将您的点添加到地图上,找到边界并倾斜相机。将相机向后倾斜,所有点仍会显示在屏幕上!这将使您开始使用屏幕上的所有点。

与示例相同,获得对 google 地图的引用。

private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.

if (mMap == null) {
    // Try to obtain the map from the SupportMapFragment.
    // mMap = mMapFragment.getMap();
    // // Check if we were successful in obtaining the map.

    // Try to obtain the map from the SupportMapFragment.
    mMap = ((SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map)).getMap();
    // use the settings maptype

    // Check if we were successful in obtaining the map.
    if (mMap != null) {
        setUpMap();
    }
}
}

让我们开始寻找地图的边界。

import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
A field for LatLngBounds and a LatLngBounds.Builder

private LatLngBounds bounds;
private LatLngBounds.Builder myLatLngBuilder;
initialize the LatLngBounds.Builder

myLatLngBuilder = new LatLngBounds.Builder();
for each point on your map.

LatLng myLatLng = new LatLng(latitude, longitude);
myLatLngBuilder.include(myLatLng);
Then when your finished adding points build your boundary.

bounds = myLatLngBuilder.build();
Now I have the bounds of all the points on my map and I can display just that area of the map. This code I lifted from the map samples.

final View mapView = getSupportFragmentManager().findFragmentById(
            R.id.map).getView();
    if (mapView.getViewTreeObserver().isAlive()) {
        mapView.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {
                    @SuppressWarnings("deprecation")
                    // We use the new method when supported
                    @SuppressLint("NewApi")
                    // We check which build version we are using.
                    @Override
                    public void onGlobalLayout() {
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                            mapView.getViewTreeObserver()
                                    .removeGlobalOnLayoutListener(this);
                        } else {
                            mapView.getViewTreeObserver()
                                    .removeOnGlobalLayoutListener(this);
                        }
                        mMap.moveCamera(CameraUpdateFactory
                                .newLatLngBounds(bounds, 50));
                    }
                });
    }

你可以做一件事,找出 2 个纬度和经度之间的距离,并检查你 got.See 的距离,它是如何工作的。 这是一个可能对你有用的技巧。

googleMap.moveCamera(CameraUpdateFactory.newLatLng(reachLocationLatLng));
if (dist > 2 && dist <= 5) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(13.0f));
mapZoomLevel = 12;
} else if (dist > 5 && dist <= 10) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
mapZoomLevel = 11;
} else if (dist > 10 && dist <= 20) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(11.0f));
mapZoomLevel = 11;
} else if (dist > 20 && dist <= 40) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10.0f));
mapZoomLevel = 10;
} else if (dist > 40 && dist < 100) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(9.0f));
mapZoomLevel = 9;
} else if (dist > 100 && dist < 200) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(8.0f));
mapZoomLevel = 8;
} else if (dist > 200 && dist < 400) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(7.0f));
mapZoomLevel = 7;
} else if (dist > 400 && dist < 700) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(6.0f));
mapZoomLevel = 7;
} else if (dist > 700 && dist < 1000) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(5.0f));
mapZoomLevel = 6;
} else if (dist > 1000) {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(4.0f));
mapZoomLevel = 5;
} else {
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14.0f));
mapZoomLevel = 14;
}

谢谢希望这对你有帮助。

现在回答太晚了 试试这条最短的路

首先获取您当前的位置经纬度,然后为您的目的地经纬度编写代码,然后使用此代码计算您当前位置和目的地位置之间的距离

private double distance(double lat1, double lon1, double lat2, double lon2) {
  double theta = lon1 - lon2;
  double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
  dist = Math.acos(dist);
  dist = rad2deg(dist);
  dist = dist * 60 * 1.1515;
   return (dist);
}
private double deg2rad(double deg) {
  return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
  return (rad * 180.0 / Math.PI);
}
  • 您永远无法获得相同的经纬度数据,因为 GPS 从您当前位置计算 95 米以显示当前位置图钉或经纬度数据。 要么你在同一个位置,你永远找不到精确的经纬度数据,这必须在点上有所不同,所以你需要得到你当前位置到你的固定经纬度数据点的距离。

  • 当你发现从你的目的地点到当前经纬度的“距离”时,然后触发此代码以动画相机和缩放。

    map.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(xxxx,xxxx),21));
    

对于上述问题,这可能是最简单的解决方案,对我来说效果很好。

将所有waypoints添加到GoogleMapOptions:camera下的目标,然后它会自动设置缩放并使地图相对于折线(给定路线)居中。

loadMap() {

let mapOptions: GoogleMapOptions = {
  camera: {
    target: this.wayPoints,
    zoom: 25,
    tilt: 30
  }
};

this.map = GoogleMaps.create('map_canvas', mapOptions);
this.map.one(GoogleMapsEvent.MAP_READY)
  .then(() => {
    console.log('Map is ready!');


   this.map.addPolyline({
      points:this.wayPoints,
      color:'#586bff',
      width: 8,
      geodesic:true,
    });
});
}

waypoints(this.wayPoints) 应采用以下格式:

[{lat: 52.33806, lng: 8.61179},
{lat: 52.33812, lng: 8.61185},
{lat: 52.33812, lng: 8.61186},
{lat: 52.33812, lng: 8.61188}]