android加入谷歌地图(2)

来源:互联网 发布:地方门户源码带手机版 编辑:程序博客网 时间:2024/06/04 19:48

本项目开发使用Android studio,本篇主要讲谷歌地图定位。

一些比较重要的点:

1.表示是要获取位置

        mGoogleApiClient = new GoogleApiClient.Builder(this)                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .addApi(LocationServices.API)                .build();

2.添加标记

MarkerOptions markerOption = new MarkerOptions();            markerOption.position(new LatLng(29.664,113.489));                //经纬度                                                                                      markerOption.title("Hello world");                               //点击后的标题            markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow));  //图片            mGoogleMap.addMarker(markerOption);


步骤

1.新建一个空Activity工程

2.在app的 build.gradle 中

    compile 'com.google.android.gms:play-services:9.8.0'
构建出错请查看“android加入谷歌地图(1)”,或加入
  dexOptions {        javaMaxHeapSize "4g"    }
3.AndroidMainfest.xml

申请权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.INTERNET" />
在application中加入,如下:

 <application    android:allowBackup="true"    android:icon="@mipmap/ic_launcher"    android:label="@string/app_name"    android:supportsRtl="true"    android:theme="@style/AppTheme">    <uses-library android:name="com.google.android.maps" />    <meta-data        android:name="com.google.android.geo.API_KEY"        android:value="your key" />        <activity android:name=".MainActivity"            android:label="map">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>
4.布局文件

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:map="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent">    <RelativeLayout        android:layout_height="match_parent"        android:layout_width="match_parent"        android:layout_weight="1">        <fragment xmlns:android="http://schemas.android.com/apk/res/android"            xmlns:tools="http://schemas.android.com/tools"            tools:context="com.gmapdemo2.googlemapdemosimple.MapsActivity"            android:id="@+id/map"            android:name="com.google.android.gms.maps.SupportMapFragment"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:layout_alignParentLeft="true"            android:layout_alignParentStart="true" >        </fragment>    </RelativeLayout></LinearLayout>

5.MainActivity

public class MainActivity extends AppCompatActivity implements        OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {    LocationRequest mLocationRequest;    GoogleApiClient mGoogleApiClient;    LatLng latLng;    GoogleMap mGoogleMap;    SupportMapFragment mMapFragment;    Marker mCurrLocation;    private static final int REQUESTCODE = 6001;    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);        mMapFragment.getMapAsync(this);    }    @Override    public void onMapReady(GoogleMap googleMap) {        mGoogleMap = googleMap;        // 允许获取我的位置        try {            mGoogleMap.setMyLocationEnabled(true);        } catch (SecurityException e) {            e.printStackTrace();        }        buildGoogleApiClient();        mGoogleApiClient.connect();    }    @Override    public void onPause() {        super.onPause();        //Unregister for location callbacks:        if (mGoogleApiClient != null) {            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, new LocationCallback() {                @Override                public void onLocationResult(LocationResult locationResult) {                    super.onLocationResult(locationResult);                }            });        }    }    protected synchronized void buildGoogleApiClient() {        Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();        mGoogleApiClient = new GoogleApiClient.Builder(this)                .addConnectionCallbacks(this)                .addOnConnectionFailedListener(this)                .addApi(LocationServices.API)                .build();    }    @Override    public void onConnected(Bundle bundle) {        Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();        Location mLastLocation = null;        try {            Log.i("0.0", LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient) + "");            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);        } catch (SecurityException e) {            e.printStackTrace();        }        if (mLastLocation != null) {           // mGoogleMap.clear();            latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());            MarkerOptions markerOptions = new MarkerOptions();            markerOptions.position(latLng);            markerOptions.title("Current Position");            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()), 15));            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.chat_loc_point));            mCurrLocation = mGoogleMap.addMarker(markerOptions);                     MarkerOptions markerOption = new MarkerOptions();     //标记测试            markerOption.position(new LatLng(27.664,113.489));                //经纬度            markerOption.title("Hello world");                               //点击后的标题            markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow));  //图片            mGoogleMap.addMarker(markerOption);                   }else{            Log.v("0.0","客户端连接"+mGoogleApiClient.isConnected());        }        mLocationRequest = LocationRequest.create();        mLocationRequest.setInterval(5000); //5 seconds        mLocationRequest.setFastestInterval(3000); //3 seconds        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, new LocationCallback() {            @Override            public void onLocationResult(LocationResult locationResult) {                super.onLocationResult(locationResult);            }        });    }    @Override    public void onConnectionSuspended(int i) {        Toast.makeText(this, "onConnectionSuspended", Toast.LENGTH_SHORT).show();    }    @Override    public void onConnectionFailed(ConnectionResult connectionResult) {        Toast.makeText(this, "onConnectionFailed", Toast.LENGTH_SHORT).show();    }    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {        switch (requestCode) {            case REQUESTCODE: {                if (grantResults.length > 0                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                    buildGoogleApiClient();                    mGoogleApiClient.connect();                } else {                }                return;            }        }    }}


原创粉丝点击