Google Map Api for Android
Posted xbw12138
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Google Map Api for Android相关的知识,希望对你有一定的参考价值。
Google Map Api for android
项目需要使用了谷歌的地图api,总结一下。
先上几个图
一、项目介绍
1.点击搜索附近的公园
这个展示的可以点击地图的任意位置获取经纬度,并标记Mark一个点,同时获取附近的公园,就是POI Search,并把所有的公园在地图上标记出来。
2.搜索当前位置附近的公园
这个是通过定位,获取附近的公园
二、实现过程
1.Google Map Api Key申请
获取api key,基本的api可以不用绑定信用卡激活账号,在安卓中的定位,显示地图等操作就不需要激活账号。搜索附近的公园等POI操作的api就需要激活账号了。关于api的获取就不细说了。
2.新建Android项目
在Android Studio中,新建一个Map Activity,这个是自带的,我们只需要在debug目录下填入申请的api key就可以了。
3.需求–定位当前位置获取兴趣点(获取附近的公园)
MainActivity
package com.example.cacp;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
//google map
private GoogleMap mMap;
double latitude;
double longitude;
//search nearby interest range
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private Context mContext;
private Button btn_list;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mContext = this;
btn_list = findViewById(R.id.btn_list);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
checkLocationPermission();
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices())
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
else
Log.d("onCreate","Google Play Services available.");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
btn_list.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
startActivity(new Intent(MainActivity.this,ListActivity.class));
);
private boolean CheckGooglePlayServices()
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS)
if(googleAPI.isUserResolvableError(result))
googleAPI.getErrorDialog(this, result,
0).show();
return false;
return true;
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap)
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
private void POI()
mMap.clear();
if (mCurrLocationMarker != null)
mCurrLocationMarker.remove();
String url = getUrl(latitude, longitude, "park");
Object[] DataTransfer = new Object[4];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
DataTransfer[2] = mContext;
DataTransfer[3] = btn_list;
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
protected synchronized void buildGoogleApiClient()
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
@Override
public void onConnected(Bundle bundle)
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
private String getUrl(double latitude, double longitude, String nearbyPlace)
StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlaceUrl.append("location="+latitude+","+longitude);
googlePlaceUrl.append("&radius="+PROXIMITY_RADIUS);
googlePlaceUrl.append("&type="+nearbyPlace);
googlePlaceUrl.append("&sensor=true");
googlePlaceUrl.append("&key="+"不让你看我的key");
Log.d("getUrl", googlePlaceUrl.toString());
return (googlePlaceUrl.toString());
@Override
public void onConnectionSuspended(int i)
@Override
public void onLocationChanged(Location location)
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null)
mCurrLocationMarker.remove();
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(MainActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
//stop location updates
if (mGoogleApiClient != null)
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
Log.d("onLocationChanged", "Exit");
POI();
@Override
public void onConnectionFailed(ConnectionResult connectionResult)
处理后的数据用来在地图上标记兴趣点,我们给了标记点点击事件,并传递了一些数据。
GetNearbyPlacesData
package com.example.cacp;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.HashMap;
import java.util.List;
public class GetNearbyPlacesData extends AsyncTask<Object, String, String>
String googlePlacesData;
GoogleMap mMap;
String url;
Context mContext;
Button btn_list;
@Override
protected String doInBackground(Object... params)
try
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
mContext = (Context) params[2];
btn_list = (Button) params[3];
DownloadUrl downloadUrl = new DownloadUrl();
googlePlacesData = downloadUrl.readUrl(url);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
catch (Exception e)
Log.d("GooglePlacesReadTask", e.toString());
return googlePlacesData;
@Override
protected void onPostExecute(String result)
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(result);
Singleton.getInstance().setListPlace(nearbyPlacesList);
ShowNearbyPlaces(nearbyPlacesList);
btn_list.setVisibility(View.VISIBLE);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList)
for (int i = 0; i < nearbyPlacesList.size(); i++)
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
final HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
@Override
public boolean onMarkerClick(Marker marker)
Intent intent = new Intent(mContext, DetailActivity.class);
intent.putExtra("placename", googlePlace.get("place_name"));
intent.putExtra("id", googlePlace.get("id"));
intent.putExtra("rating", "rating :" + googlePlace.get("rating"));
intent.putExtra("info", googlePlace.get("lat")+","+googlePlace.get("lng"));
final String photoUrl = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference="+ googlePlace.get("photo_reference") +"&key=不让你看我的key";
intent.putExtra("photourl", photoUrl);
mContext.startActivity(intent);
return false;
);
4.需求–任意点击屏幕位置获取附近兴趣点(获取附近的公园)
我们只是把定位那一部分换成了监听点击地图事件
GoogleMap点击事件监听
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
@Override
public void onMapClick(LatLng latLng)
markPark(latLng);
);
Mark标记点
private void markPark(LatLng latLng)
mMap.clear();
if (mCurrLocationMarker != null)
mCurrLocationMarker.remove();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
POI(latLng);
Toast.makeText(Main2Activity.this,String.format("latitude:%.3f longitude:%.3f",latLng.latitude,latLng.longitude),Toast.LENGTH_LONG).show();
完整代码
package com.example.cacp;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class Main2Activity extends FragmentActivity implements OnMapReadyCallback
private GoogleMap mMap;
private Marker mCurrLocationMarker;
private int PROXIMITY_RADIUS = 10000;
private Context mContext;
private Button btn_list;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mContext = this;
btn_list = findViewById(R.id.btn_list);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
checkLocationPermission();
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices())
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
else
Log.d("onCreate","Google Play Services available.");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
private boolean CheckGooglePlayServices()
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS)
if(googleAPI.isUserResolvableError(result))
googleAPI.getErrorDialog(this, result,
0).show();
return false;
return true;
@Override
public void onMapReady(GoogleMap googleMap)
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
mMap.setMyLocationEnabled(true);
else
mMap.setMyLocationEnabled(true);
markPark(new LatLng(52.388,-1.291));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
@Override
public void onMapClick(LatLng latLng)
markPark(latLng);
);
private void markPark(LatLng latLng)
mMap.clear();
if (mCurrLocationMarker != null)
mCurrLocationMarker.remove();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
POI(latLng);
Toast.makeText(Main2Activity.this,String.format("latitude:%.3f longitude:%.3f",latLng.latitude,latLng.longitude),Toast.LENGTH_LONG).show();
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission()
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION))
ActivityCompat.requestPermissions(this,
new String[]Manifest.permission.ACCESS_FINE_LOCATION,
MY_PERMISSIONS_REQUEST_LOCATION);
else
ActivityCompat.requestPermissions(this,
new String[]Manifest.permission.ACCESS_FINE_LOCATION,
MY_PERMISSIONS_REQUEST_LOCATION);
return false;
else
return true;
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults)
switch (requestCode)
case MY_PERMISSIONS_REQUEST_LOCATION:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
mMap.setMyLocationEnabled(true);
else
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
return;
private void POI(LatLng latLng)
String url = getUrl(latLng.latitude, latLng.longitude, "park");
Object[] DataTransfer = new Object[4];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
DataTransfer[2] = mContext;
DataTransfer[3] = btn_list;
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
private String getUrl(double latitude, double longitude, String nearbyPlace)
StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlaceUrl.append("location="+latitude+","+longitude);
googlePlaceUrl.append("&radius="+PROXIMITY_RADIUS);
googlePlaceUrl.append("&type="+nearbyPlace);
googlePlaceUrl.append("&sensor=true");
googlePlaceUrl.append("&key="+"不给你看我的key");
Log.d("getUrl", googlePlaceUrl.toString());
return (googlePlaceUrl.toString());
两部分的xml文件都一样,都可以用Android Studio自动生成的Map Activity的布局文件
三、需要demo的请留言
需要demo的请留言
以上是关于Google Map Api for Android的主要内容,如果未能解决你的问题,请参考以下文章
com.android.build.api.transform.TransformException:java.util.zip.ZipException:重复条目:com/google/androi
打开eclipse后应该怎样安装 Google map API ?在Android sDK Manager列表中没有找到Google map API 这应该