Google Map开发总结(Android)| Gjson

/ Android世界 / 0 条评论 / 9813浏览
  1. 添加依赖及注册key compile 'com.google.android.gms:play-services-maps:10.2.1' compile 'com.google.android.gms:play-services:10.2.1' 注册key地址: https://console.developers.google.com,选择凭据进行注册,注册完记得在信息中心启用相应的API

  2. 在AndroidManifest中添加key <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" />

  3. 初始化显示地图 在要显示地图的layout中加入 <fragment android:id="@+id/map" class="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" />

  4. 在activity中进行初始化 private GoogleMap mMap; private GoogleApiClient mGoogleApiClient; private Location mLastLocation; private LocationRequest mLocationRequest;// 位置请求 SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); //获取map控件id mapFragment.getMapAsync(onMapReadyCallback); //设置回调 mGoogleApiClient = new GoogleApiClient.Builder(this) //初始化GoogleApiClient .addConnectionCallbacks(connectedListener) //添加连接回调监听 .addOnConnectionFailedListener(connectionFailedListener) //添加连接失败回调监听 .addApi(LocationServices.API) //添加需要使用到的API .addApi(Places.PLACE_DETECTION_API) .addApi(Places.GEO_DATA_API) .build();

  5. 地图设置参考,记得在onMapReadyCallback里进行设置,地图没准备好,会出现异常。 google_map_1

  6. 地图加载完成的回调。 google_map_2

  7. 客户端连接回调。 google_map_3

  8. 位置监听。 // 位置监听 private LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { // 第一次定位时,将地图位置移动到当前位置 if (isFristLocation) { isFristLocation = false; mLastLocation = location; double startLatitude1 = mLastLocation.getLatitude(); double startLongitude1 = mLastLocation.getLongitude(); mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(startLatitude1, startLongitude1))); stopLocationUpdates(); } } }; //开始定位 protected void startLocationUpdates() { if (mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListener); } } //停止定位 protected void stopLocationUpdates() { if (mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListener); } }

  9. 生命周期。
    google_map_4

  10. 添加marker、移动到指定坐标、画线方法 添加marker mGoogleMap.addMarker(new MarkerOptions().position(marker的坐标).icon(BitmapDescriptorFactory.fromResource(marker图片资源))); 移动到指定坐标 mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(你要的坐标, 地图放大比例)); mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(你要的坐标)); 画线方法 PolylineOptions polylineOptions = new PolylineOptions().addAll(坐标集合).width(10).color(Color.BLUE); Polyline line0 = mGoogleMap.addPolyline(polylineOptions);

  11. 其他参考资料 https://developers.google.com/maps/?hl=zh-cn