放大特定路线谷歌地图

时间:2016-09-23 09:07:09

标签: android google-maps-android-api-2 marker polyline

enter image description here below is screen shot @antonio what i get after removing line

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

下面
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());*/

                }
            });
        }

    }
}

此处最后一次暂停是布尔值,表示它是否是用于指示红色折线的暂停点。

但它不起作用。感谢任何帮助。

9 个答案:

答案 0 :(得分:22)

尝试以这种方式实施

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

<强>更新

查看图像后,地图上方有布局。因此,需要您设置可变填充。你可以这样做

routePadding = 0

注意:设置变量填充时,可以初始化left = right = 10; 在您的情况下,近似值为:bottom=100top=200Recommendation: You can calculate the height of those (top and bottom) layouts in pixels and then set padding accordingly.。设置完成后,您可以根据自己的要求校准。

$('p a').replaceWith(function() { return document.createTextNode($(this).text()) })

答案 1 :(得分:6)

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

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);
    }
});

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

答案 2 :(得分:4)

您需要将构成折线的所有点都包含在mapBounds对象中。

此外,您正在使用animateCamera更新相机,然后使用moveCamera移动相机。第二次摄像头更新会覆盖第一次。只需删除该行

即可
googleMap.moveCamera(CameraUpdateFactory.zoomOut());

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

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

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

答案 3 :(得分:3)

我实施了一个类似于@ 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
            }
        }
    }

答案 4 :(得分:2)

var customerNameDict = ["firstName":"karthi","LastName":"alagu","MiddleName":"prabhu"];
var clientNameDict = ["firstName":"Selva","LastName":"kumar","MiddleName":"m"];
var employeeNameDict = ["firstName":"karthi","LastName":"prabhu","MiddleName":"kp"];


var attributeValue = "karthi";
var arrNames:Array = [customerNameDict,clientNameDict,employeeNameDict];
var namePredicate =NSPredicate(format: "firstName like %@",attributeValue);


let filteredArray = arrNames.filter { namePredicate.evaluateWithObject($0) };
println("names = ,\(filteredArray)");

如果有帮助,请尝试

答案 5 :(得分:2)

你可以做一件事,找出2纬度和经度之间的距离,并检查你得到的距离。看,它是如何工作的。 这可能对你有用。

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;
}

谢谢希望这会对你有所帮助。

答案 6 :(得分:0)

我是怎么做到的。

Android - plotting gps coordinate on custom map

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

相同的示例获得对谷歌地图的引用。

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));
                    }
                });
    }

答案 7 :(得分:0)

现在回答很晚  尝试用这种最短的方式

首先获取当前位置latlongs然后获取目标lat long的写入代码,然后使用此代码计算当前位置和目标位置之间的距离

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);
}
  • 由于距离当前位置95米的GPS数量显示当前位置引脚或纬度较长的数据,因此您永远无法获得相同的lat long数据。 要么你是同一个地方你永远找不到确切的lat长数据,这必须有不同的点数,这样你需要将当前位置与你的修复lat长数据点保持距离。

  • 当你发现&#34; 距离&#34;从你的目的地点到当前lat长,然后激活此代码以动画相机和缩放。

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

答案 8 :(得分:0)

对于上述问题,这可能是最简单的解决方案,对我来说非常有用。

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

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,
    });
});
}

航点(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}]