1. 安装开发环境,参照Google Maps Android API v2 的Getting Started,具体不详述了,程序跑起来,能看到google地图就行。
2. 添加marker:
mMap.addMarker(new MarkerOptions().position(new LatLng(10, 10)).title("Marker"));即可添加一个简单的marker,关于marker更多的内容可以查看Markers
可以将上述调用的返回值保存起来,Marker marker = mMap.addMarker(new MarkerOptions().position(new LatLng(10, 10)).title("Marker"));作为当前位置的标识,随着经纬度的改变,调用marker.position(new LatLng(latitude, longitude));就会改变marker的位置。如果需要以当前位置显示在地图的中心点,调用mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude)));,更多内容请查看Moving the camera.
3. 根据两点自动缩放Position1(latitude1, longitude1), Position2(latitude2, longitude2):
3.1 只需要两个点都显示出来:
LatLngBounds center = new LatLngBounds(new LatLng(latitude1<latitude2?latitude1:latitude2, longitude1<longitude2?longitude1:longitude2), new LatLng(latitude1>latitude2?latitude1:latitude2, longitude1>longitude2?longitude1:longitude2));
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(center, 0));注意LatLngBounds的构造函数,第一个LatLng的参数为(south,west),第二个LatLng的参数为(north,east)
3.2 Position1显示在中心点,同时显示Position2:
先计算Position1和Position2的水平(经度差horizontal)和垂直(纬度差vertical)方向的的差值,center = new LatLngBounds(new LatLng(latitude1-vertical, longitude1-horizontal), new LatLng(latitude1+vertical, longitude1+horizontal));
4. 如果出现
java.lang.IllegalStateException: Error using newLatLngBounds(LatLngBounds, int): Map size can't be 0. Most likely, layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions.
是因为地图还没有加载完成,就开始change view,可以在地图加载完成在change:
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded()
{
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(center, 0));
}
});