google地图demo 博客分类: FY_Android androidgooglegoogle map地图
--------------------------------------------准备工作-----------------------------------------
官网文档地址:https://developers.google.com/maps/documentation/android/
按照文档申请API_KEY,安装Google Play services
--------------------------------------------AndroidManifest.xml---------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zfibs.travels"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<permission
android:name="com.zfibs.travels.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.zfibs.travels.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!-- The following two permissions are not required to use Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.zfibs.travels.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MapActivity"></activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBZpHp0fZJktlQlvb8czIP_hEAaZYPLd8w" />
</application>
</manifest>
--------------------------------------------Layout activity_main.xml--------------------
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/loaction_but"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/loaction_str" />
<Button
android:id="@+id/scenic_but"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/scenic_str" />
<Button
android:id="@+id/hostel_but"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hostel_str" />
<Button
android:id="@+id/restaurant_but"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/restaurant_str" />
<Button
android:id="@+id/shop_but"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/shop_str" />
<Button
android:id="@+id/draw_line"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/draw_line" />
</LinearLayout>
--------------------------------------------Layout activity_map.xml---------------------
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
--------------------------------------------Activity MainActivity.java--------------------
public class MainActivity extends Activity {
/** 当前位置按钮 */
private Button loaction_but = null;
/** 风景按钮 */
private Button scenic_but = null;
/** 旅店按钮 */
private Button hostel_but = null;
/** 餐厅按钮 */
private Button restaurant_but = null;
/** 购物按钮 */
private Button shop_but = null;
/** 多点连线 */
private Button draw_line = null;
/** 跳转意图 */
private Intent activityIntent = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
setListeners();
activityIntent = new Intent(this, MapActivity.class);
}
private void findViews() {
loaction_but = (Button) findViewById(R.id.loaction_but);
scenic_but = (Button) findViewById(R.id.scenic_but);
hostel_but = (Button) findViewById(R.id.hostel_but);
restaurant_but = (Button) findViewById(R.id.restaurant_but);
shop_but = (Button) findViewById(R.id.shop_but);
draw_line = (Button) findViewById(R.id.draw_line);
}
private void setListeners() {
loaction_but.setOnClickListener(new OnClickListenerImpl(0));
scenic_but.setOnClickListener(new OnClickListenerImpl(1));
hostel_but.setOnClickListener(new OnClickListenerImpl(2));
restaurant_but.setOnClickListener(new OnClickListenerImpl(3));
shop_but.setOnClickListener(new OnClickListenerImpl(4));
draw_line.setOnClickListener(new OnClickListenerImpl(5));
}
/* 设置按钮的事件类 */
public class OnClickListenerImpl implements OnClickListener {
private int index = 0;
/** 构造方法 */
public OnClickListenerImpl(int index) {
this.index = index;
}
@Override
public void onClick(View v) {
activityIntent.putExtra("index", index);
startActivity(activityIntent);
}
}
}
--------------------------------------------Activity MapActivity.java---------------------
package com.zfibs.travels;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class MapActivity extends FragmentActivity {
private static final String api_key = "AIzaSyBZpHp0fZJktlQlvb8czIP_hEAaZYPLd8w";
private static final int radius = 5000;
private static final String language = "zh-CN";
private static final String keywords = "";
/** Google地图类 */
private static GoogleMap googleMap = null;
/** 位置管理器类 */
private LocationManager locationManager = null;
/** 查询得到多点List */
private List<LatLng> liLatLngs = null;
/** Google地图UI设置实体类 */
private UiSettings uiSettings = null;
/** 查询附近信息返回的List信息 */
private List<Map<String, String>> listMaps = null;
/** 最佳的Provide */
private String fineProvide = "";
/** 当前位置信息 */
private LatLng latLng = new LatLng(42.730070, -73.690570);
/** 搜索位置详细信息 */
private Map<String, String> locatInfo = null;
/** 查询时候的进度框 */
private ProgressDialog progressDialog = null;
/** 查询附近信息的Type值 */
private String types = "";
/** Google地图工具类 */
private GoogleUtil googleUtil = null;
/** 匹配的名称 */
private String name = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
initActivityData();
dome(this.getIntent().getIntExtra("index", 0));
}
/**
* 初始化Activity基础数据信息
*/
private void initActivityData() {
// 初始化地图信息
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = supportMapFragment.getMap();
if (null != googleMap) {
uiSettings = googleMap.getUiSettings();
uiSettings.setMyLocationButtonEnabled(true);
} else {
Toast.makeText(this, "加载地图失败", Toast.LENGTH_SHORT).show();
}
googleUtil = new GoogleUtil();
// 初始化位置管理器
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getFineProvider();
locationManager.requestLocationUpdates(fineProvide, 1000, 0, locationListener);
}
private void dome(int index){
switch (index) {
case 0:
getFineProvider();// 获取当前位置的坐标
new SearchAsyncTask(0).execute();
break;
case 1:// 风景
types = "painter";
new SearchAsyncTask(1).execute();
break;
case 2:// 旅馆
types = "lodging";
new SearchAsyncTask(1).execute();
break;
case 3:// 餐厅
types = "food|restaurant";
new SearchAsyncTask(1).execute();
break;
case 4:// 购物
types = "shopping_mall";
new SearchAsyncTask(1).execute();
break;
case 5:// 多点连线
dealListPoints();
break;
}
}
/**
* 处理多个点连线的信息
*/
private void dealListPoints() {// 根据数据库查询经过的经度和纬度信息
liLatLngs = new LinkedList<LatLng>();
liLatLngs.add(new LatLng(37.35, -122.0));
liLatLngs.add(new LatLng(37.45, -122.0));
liLatLngs.add(new LatLng(37.45, -122.2));
liLatLngs.add(new LatLng(37.35, -122.2));
liLatLngs.add(new LatLng(37.35, -122.0));
PolylineOptions rectOptions = new PolylineOptions().addAll(liLatLngs);
Polyline polyline = googleMap.addPolyline(rectOptions);
polyline.setColor(Color.RED);
for (int i = 0; i < liLatLngs.size(); i++) {
// 设置标识信息
googleMap.addMarker(new MarkerOptions().position(liLatLngs.get(i)).title("名称").snippet("描述...")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
if (i == liLatLngs.size() - 1) {
setMapCenter(liLatLngs.get(i));
}
}
}
/**
* 获取最佳LocationProvifer
*/
@SuppressWarnings("unused")
private void getFineProvider() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
criteria.setAltitudeRequired(false); // 不要求海拔
criteria.setBearingRequired(false); // 不要求方位
criteria.setCostAllowed(false); // 不允许有话费
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
this.fineProvide = locationManager.getBestProvider(criteria, true);
if (null == this.fineProvide) {
this.fineProvide = LocationManager.GPS_PROVIDER;
}
Location location = null;
// while (null != location) {
location = locationManager.getLastKnownLocation(fineProvide);
// }
if (null != location) {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
setMapCenter(latLng);
} else {
Toast.makeText(this, "定位失败!", Toast.LENGTH_SHORT).show();
}
}
/**
* 处理搜索和定位的信息类
*
* @author fy
*
*/
private class SearchAsyncTask extends AsyncTask<Integer, String, Integer> {
private int index = 0;
public SearchAsyncTask(int index) {
this.index = index;
progressDialog = ProgressDialog.show(MapActivity.this, "请稍等...", "获取数据中...", true);
progressDialog.setCancelable(true);
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
// 更新UI
if (this.index == 0) {
if (null != locatInfo) {
googleMap.addMarker(new MarkerOptions().position(latLng).title(locatInfo.get("name"))
.snippet(locatInfo.get("address")).icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
setMapCenter(latLng);
}
} else {
if (null != listMaps && listMaps.size() > 0) {
for (int i = 0; i < listMaps.size(); i++) {
// 设置标识信息
googleMap.addMarker(new MarkerOptions().position(latLng).title(listMaps.get(i).get("name"))
.snippet(listMaps.get(i).get("address")).icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
}
}
}
}
@Override
protected Integer doInBackground(Integer... arg0) {
try {
if (index == 0) {// 定位
if (null != latLng) {
locatInfo = googleUtil.queryByLatLng(latLng, language);
}
} else {// 搜索附近信息
if (null != latLng) {
listMaps = googleUtil.queryByCondition(api_key, latLng, radius, keywords, language, name, types);
}
}
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
return null;
}
}
/**
* 位置发生改变时候的监听器
*/
LocationListener locationListener = new LocationListener() {
// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
// Provider被enable时触发此函数,比如GPS被打开
@Override
public void onProviderEnabled(String provider) {
}
// Provider被disable时触发此函数,比如GPS被关闭
@Override
public void onProviderDisabled(String provider) {
}
// 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
@Override
public void onLocationChanged(Location location) {
if (location != null) {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
Log.i("fy", "经度" + location.getLatitude());
Log.i("fy", "纬度" + location.getLongitude());
// Toast.makeText(getApplicationContext(), + "| , Toast.LENGTH_LONG).show();
googleMap.addMarker(new MarkerOptions().position(latLng).title("名称...").snippet("描述..."));
}
}
};
/**
* 设置视图的中心
*
* @param latLng
*/
public static void setMapCenter(LatLng latLng) {
// 设置显示的级别
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomIn());
// Zoom out to zoom level 10, animating with a duration of 2 seconds.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2, null);
// 构造一个CameraPosition关注山景和动画镜头的位置。
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng)// 集映射到中心的山景
.zoom(17).bearing(90) // 设置相机的方向东
.tilt(30) // 设置相机的倾斜30度
.build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/***
* 监听调用返回键的事件
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (null != progressDialog && progressDialog.isShowing()) {
progressDialog.dismiss();
} else {
finish();
}
return false;
}
return false;
}
@Override
protected void onDestroy() {
if (null != progressDialog) {
progressDialog.cancel();
}
super.onDestroy();
}
}
--------------------------------------------工具类 GoogleUtil.java------------------------
package com.zfibs.travels;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.android.gms.maps.model.LatLng;
/**
* Google Map的搜索工具
*
* @author fy
*
*/
public class GoogleUtil {
private String URL_API1 = "http://maps.googleapis.com/maps/api/geocode/json?";
private String URL_API2 = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String API_KEY = "AIzaSyBZpHp0fZJktlQlvb8czIP_hEAaZYPLd8w";
/**
* 根据坐标点 查询当前位置
*
* @param latLng
* @return
*/
public Map<String, String> queryByLatLng(LatLng latLng, String language) throws Exception {
String URL_API = this.URL_API1;
Map<String, String> map = new HashMap<String, String>();
StringBuffer buf = new StringBuffer();
InputStream input = null;
URL_API += "latlng=" + latLng.latitude + "," + latLng.longitude;
URL_API += "&language=" + language + "&sensor=false";
// http://maps.googleapis.com/maps/api/geocode/json?latlng=,&sensor=false
System.out.print("请求的URL=" + URL_API);
try {
URL url = new URL(URL_API);
input = url.openStream();
Scanner scan = new Scanner(input);
while (scan.hasNext()) {
buf.append(scan.next()); // 所有的数据都保存在字符串里面
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (input != null) {
input.close();
}
}
System.out.println("查询得到的数据=" + buf.toString());
JSONObject allData = new JSONObject(buf.toString());
// 获取连接状态
String status = allData.getString("status");
if ("OK".equals(status)) {
JSONArray jsonArr = allData.getJSONArray("results");
JSONObject jsonObj = jsonArr.getJSONObject(0);
map.put("address", jsonObj.getString("formatted_address"));
// map.put("icon", jsonObj.getString("icon"));
map.put("name", jsonObj.getString("name"));
System.out.print("查询得到的数据address=" + jsonObj.getString("formatted_address"));
JSONObject locationJsonObj = jsonObj.getJSONObject("geometry").getJSONObject("location");
map.put("latitude", locationJsonObj.getString("lat"));
map.put("longitude", locationJsonObj.getString("lng"));
map.put("status", "OK");
} else {
map.put("status", "FAIL");
}
return map;
}
/**
* 根据传入的条件信息查询附近信息
*
* @param key API 密钥
* @param location 即要在其周围检索地方信息的纬度/经度。必须指定为纬度、经度。
* @param radius 范围
* @param sensor 请求的设备是否会使用 GPS 等位置传感器
* @param keyword 方建立索引的全部内容相匹配的字词(可选)
* @param language 语言代码(可选)
* @param name 地方信息的名称进行匹配的字词(可选)
* @param types 指定类型相匹配的地方信息,类型应使用竖线符号 (type1|type2|etc) 进行分隔(可选)
* @return List<Map<String, String>>
*/
public List<Map<String, String>> queryByCondition(String key, LatLng latLng, int radius, String keyword,
String language, String name, String types) throws Exception {
String URL_API = this.URL_API2;
List<Map<String, String>> listMaps = new LinkedList<Map<String, String>>();
// *******************************************组装请求路径信息*********************//
// 例子:https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AddYourOwnKeyHere
URL_API += "location=" + latLng.latitude + "," + latLng.longitude + "&radius=" + radius + "";
if (null != keyword && keyword.length() > 0) {// 关键词
URL_API += "&keyword=" + keyword;
}
if (null != language && language.length() > 0) {// 语言
URL_API += "&language=" + language;
}
if (null != name && name.length() > 0) {// 匹配名称
URL_API += "&name=" + name;
}
if (null != types && types.length() > 0) {// 类型
URL_API += "&types=" + types;
}
URL_API += "&sensor=true";
URL_API += "&key=" + API_KEY + "";
System.out.print("请求的URL=" + URL_API);
// *******************************************获取查询得到的返回值****//
StringBuffer buf = new StringBuffer();
InputStream input = null;
try {
URL url = new URL(URL_API);
input = url.openStream();
Scanner scan = new Scanner(input);
while (scan.hasNext()) {
buf.append(scan.next()); // 所有的数据都保存在字符串里面
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (input != null) {
input.close();
}
}
System.out.println("查询得到的数据=" + buf.toString());
JSONObject allData = new JSONObject(buf.toString());
// 获取连接状态
String status = allData.getString("status");
if ("OK".equals(status)) {
JSONArray jsonArr = allData.getJSONArray("results");
for (int i = 0; i < jsonArr.length(); i++) {
Map<String, String> map = new HashMap<String, String>();
JSONObject jsonObj = jsonArr.getJSONObject(i);
map.put("address", jsonObj.getString("formatted_address"));
map.put("icon", jsonObj.getString("icon"));
map.put("name", jsonObj.getString("name"));
System.out.println("查询得到的数据address=" + jsonObj.getString("formatted_address"));
JSONObject locationJsonObj = jsonObj.getJSONObject("geometry").getJSONObject("location");
map.put("latitude", locationJsonObj.getString("lat"));
map.put("longitude", locationJsonObj.getString("lng"));
listMaps.add(map);
}
}
return listMaps;
}
}
--------------------------------------------运行效果-----------------------------------------
<!--EndFragment-->