GOOGLE MAP API是Android的靓点之一,我们可以创建一个MapActivity的子类,将MapView显示于其上即可,可以用MapController来控制显示的坐标、地图模式和视野高度,处理起来非常简单。
完整代码如下:
public class MapTest extends MapActivity {
private MapView mapView;
private MapController mc;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
mapView = (MapView) findViewById(R.id.map);
mapView.setTraffic(true);
mc = mapView.getController();
GeoPoint gp = new GeoPoint((int) (30.659259 * 1000000), (int) (104.065762 * 1000000)); //地理坐标
mc.animateTo(gp);
mc.setZoom(12);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
mapview.xml内容如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.google.android.maps.MapView android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0mHnPl2NS9XPKx6pKwJriV2Wj-mEHSh71yyX_SQ"
/>
</RelativeLayout>
注意:
1、你要申请一个自己的apiKey;
2、不要忘了设置互联网访问权限。
本节主要是介绍一下gps的使用,google map和gps的结合是android上主要应用之一,android market中,此类产品所占比例不小。
我们在上节的代码中添加如下内容:
LocationManager lm;
MyLocationListener locationListener;
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
缺少MyLocationListener吧?那我们就创建一个MyLocationListener,要实现LocationListener中的几个方法,LocationListener的功能我就不用再说了吧?
我吧代码贴出来,一目了然。
// 下面是从GPS获取坐标的监听,暂时没有使用
public class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
if (loc != null) {
Log.d("MapTest", "Location changed : Lat: " + loc.getLatitude() + " Lng: " + loc.getLongitude());
GeoPoint p = new GeoPoint((int) (loc.getLatitude() * 1E6), (int) (loc.getLongitude() * 1E6));
mc.animateTo(p);
mc.setZoom(16);
mapView.invalidate();
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
注意事项:
又是权限的问题,我全列出来,随便用哪个了。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
Android map and location
最新推荐文章于 2025-02-17 13:35:54 发布