41.3.2 风景区展示实例
3.完成功能清单AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sharpandroid.ScenicDisplay"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/
app_name">
<activity android:name=".SciencDisplayActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="com.google.android.maps" />
</application>
<uses-sdk android:minSdkVersion="7" />
<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">
</uses-permission>
<uses-permission android:name="com.google.android.maps">
</uses-permission>
</manifest>
4.main.xml文件
在此布局文件中我们需要三个组件,分别为MapView组件、zoom 界面组件、TextView控件。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/
android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="50px"
android:background="#F0FFFF"
android:textColor="#0000CD"
android:padding="8dip"
android:text=""
/>
<com.google.android.maps.MapView
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/textview"
android:apiKey="0msHaq9AU6OJwZR3mN1DstI-wNKx9p4Yio_bncQ"
android:clickable="true"
/>
<LinearLayout
android:id="@+id/zoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
></LinearLayout>
</RelativeLayout>
5.ScenicDisplay.java中的代码
package com.sharpandroid.ScenicDisplay;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;
public class ScenicDisplay extends MapActivity {
private MapView mapView;
private MapController mapController;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) this.findViewById(R.id.map);
//取得mapView 控件
mapController = mapView.getController();
mapController.setZoom(17);
mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
}
protected static final int MENU_CC = Menu.FIRST;
protected static final int MENU_SUN = Menu.FIRST+1;
protected static final int MENU_TYHJ = Menu.FIRST+2;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_CC, 0,"八达岭长城")
.setIcon(R.drawable.imagescc)
.setAlphabeticShortcut('a');
menu.add(0, MENU_SUN, 0, "太阳岛")
.setIcon(R.drawable.imagessun)
.setAlphabeticShortcut('b');
menu.add(0, MENU_TYHJ, 0, "天涯海角")
.setIcon(R.drawable.imagesty)
.setAlphabeticShortcut('c');
return super.onCreateOptionsMenu(menu);
}
GeoPoint position_cc = new GeoPoint(
(int) (40.362643 * 1000000),
(int) (116.019793 * 1000000)
);
GeoPoint position_sun = new GeoPoint(
(int) (45.789361 * 1000000),
(int) (126.600048 * 1000000)
);
GeoPoint position_ty = new GeoPoint(
(int) (18.292023 * 1000000),
(int) (109.347711 * 1000000)
);
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_CC:
mapController.animateTo(position_cc);
break;
case MENU_SUN:
mapController.animateTo(position_sun);
break;
case MENU_TYHJ:
mapController.animateTo(position_ty);
}
return super.onOptionsItemSelected(item);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
6.风景区图标、绘图的添加
首先我们想在Map上添加我们想要的图标信息,实现代码如下:
private class positionOverlay extends ItemizedOverlay<OverlayItem>{
private final int mRadius = 5;
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public positionOverlay(Drawable drawable) {
super(boundCenter(drawable));
items.add(
new OverlayItem(position_cc, "中国八达岭长城", "21度"));
items.add(
new OverlayItem(position_sun, "中国首批5A", "16度"));
items.add(
new OverlayItem(position_ty, "中国名旅", "32度"));
populate();
}
@Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return items.get(i);
}
@Override
public int size() {
// TODO Auto-generated method stub
return items.size();
}
@Override
public boolean onTap(int index) {
Toast.makeText(SciencDisplayActivity.this, "今天的气温是"+items.
get(index).getSnippet(),Toast.LENGTH_SHORT).show();
return true;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Projection projection = mapView.getProjection();
for (int index = size() - 1; index >= 0; index--) {
OverlayItem overLayItem = getItem(index);
String title = overLayItem.getTitle();
Point point = projection.toPixels(overLayItem.getPoint(), null);
RectF oval = new RectF(point.x - mRadius,point.y - mRadius,
point.x + mRadius,point.y + mRadius);
Paint paint = new Paint();
paint.setColor(Color.CYAN);
paint.setAntiAlias(true);
paint.setFakeBoldText(true);
Paint backPaint = new Paint();
backPaint.setColor(Color.RED);
backPaint.setAntiAlias(true);
RectF backRectF = new RectF(
point.x + 40+ mRadius,point.y - 3*mRadius,
point.x +65,point.y + 2*mRadius
);
/* 文字设置 */
Paint paintText = new Paint();
paintText.setColor(Color.BLUE);
paintText.setTextSize(25);
canvas.drawOval(oval, paint);
canvas.drawRoundRect(backRectF, 10, 10, backPaint);
canvas.drawText(title, point.x, point.y, paintText);
}
super.draw(canvas, mapView, shadow);
}
}
7.风景区简介添加
关键代码实现:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_CC:
mapController.animateTo(position_cc);
showDialog("世界文化遗产、国家5A级景区、国家重点文物保护单位、国家重
点风景名胜区" +"中国旅游胜地四十佳"之首、全国文明旅游风景示范区.");
break;
case MENU_SUN:
mapController.animateTo(position_sun);
textView.setText("是国内最大的城市中心江漫滩湿地景观,周边栽植北方特有的有
菩提树之称的糠椴…");
break;
case MENU_TYHJ:
if (textView.getText().toString()!=null) {
textView.setText("有热带海滩花岗岩风景区、购物区和度假村组成集成热带
海洋风光…." );
}
mapController.animateTo(position_ty);
}
return super.onOptionsItemSelected(item);
}
41.4.2 GPS旅游导航仪实例
1.第一部分,功能实现
AndroidManifest.xml中的代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sharpandroid.navigation"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label=
"@string/app_name">
<activity android:name=".TravelTracks"
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="com.sharpandroid.navigation.
DirectionTracks" android:label="Navigation">
<intent-filter>
<category android:name="android.intent.category.
LAUNCHER"></category>
<action android:name="android.intent.action.MAIN"></action>
</intent-filter>
</activity>
<uses-library android:name="com.google.android.maps" />
<activity android:name="com.sharpandroid.navigation.
PositionConvert" android:label="Navigation">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER">
</category>
<action android:name="android.intent.action.MAIN"></action>
</intent-filter>
</activity>
<uses-library android:name="com.google.android.maps" />
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
<uses-permission android:name="com.google.android.maps">
</uses-permission>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>
TravelNavigation/res/values中定义了两个文件。
(1)string.xml文件在这个文件中定义了整个项目中用到的资源文字串。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, DaoTracks!</string>
<string name="app_name">旅游导航仪</string>
<string name="Resolvebutton">位置解析</string>
<string name="NavigationButton">路况导航仪</string>
<string name="str_longitude">经度(Longitude):</string>
<string name="str_latitude">纬度(Latitude):</string>
<string name="str_default_address">八达岭长城</string>
<string name="str_button1">规划路径</string>
<string name="str_button2">+</string>
<string name="str_button3">-</string>
<string name="str_button4">查询</string>
<string name="str_button5">卫星视图(开)</string>
<string name="str_button6">卫星视图(关)</string>
<string name="str_to">前往:</string>
<string name="str_my_location">目前所在地址:</string>
</resources>
(2)color.xml文件在这个文件中定义了整个项目中用到的颜色。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="darkgray">#808080</drawable>
<drawable name="white">#FFFFFF</drawable>
<drawable name="blue">#0000FF</drawable>
</resources>
TravelNavigation/res/layout中定义了三个文件。
(1)main.xml,在主页面中定义了一个TextView 控件和两个Button控件,分别作为进入两个功能的“入口”。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="出行好帮手"
android:gravity="center"
/>
<Button android:id="@+id/Resolvebutton"
android:layout_width="200px"
android:layout_height="wrap_content"
android:text="@+string/Resolvebutton"
></Button>
<Button android:id="@+id/NavigationButton"
android:layout_width="200px"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@+string/NavigationButton"
></Button>
</LinearLayout>
(2)navigation.xml,在此文件中定义了一个TextView控件、一个EditText控件、三个Button控件、一个MapView控件并且用LinearLayout布局方式进行横向排列。
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/white"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- 建立一个TextView
-->
<TextView android:id="@+id/myTextView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@drawable/blue"
android:text="@string/hello" />
- <!-- 建立一个EditText
-->
<EditText android:id="@+id/myEditText1"
android:layout_width="180px"
android:layout_height="wrap_content"
android:text="" />
- <LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
- <!-- 建立第一个Button
-->
<Button android:id="@+id/myButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_button1" />
- <!-- 建立第二個Button
-->
<Button android:id="@+id/myButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_button2" />
- <!-- 建立第三個Button
-->
<Button android:id="@+id/myButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_button3" />
</LinearLayout>
-
<com.google.android.maps.MapView
android:id="@+id/myMapView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0msHaq9AU6OJwZR3mN1DstI-wNKx9p4Yio_bncQ" />
</LinearLayout>
(3)resolve.xml,在这个文件中用关系型布局方式AbsoluteLayout定义了两个TextView、三个Button、两个EditText、一个ToggleButton和一个MapView控件。
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/layout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/white"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<!-- 建立第一个EditText
-->
<EditText
android:id="@+id/myEdit1"
android:layout_width="105px"
android:layout_height="40px"
android:textSize="16sp"
android:layout_x="130px"
android:layout_y="12px"
android:numeric="decimal"
>
</EditText>
<!-- 建立第二个EditText
-->
<EditText
android:id="@+id/myEdit2"
android:layout_width="105px"
android:layout_height="40px"
android:textSize="16sp"
android:layout_x="130px"
android:layout_y="52px"
android:numeric="decimal"
>
</EditText>
<!-- 建立第一个TextView
-->
<TextView
android:id="@+id/myText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_longitude"
android:textColor="@drawable/blue"
android:layout_x="10px"
android:layout_y="22px"
>
</TextView>
<!-- 建立第一个TextView
-->
<TextView
android:id="@+id/myText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_latitude"
android:textColor="@drawable/blue"
android:layout_x="10px"
android:layout_y="62px"
>
</TextView>
<!-- 建立第一个Button
-->
<Button
android:id="@+id/myButton1"
android:layout_width="77px"
android:layout_height="45px"
android:text="@string/str_button4"
android:layout_x="240px"
android:layout_y="12px"
>
</Button>
<!-- 建立第二个Button
-->
<Button
android:id="@+id/myButton2"
android:layout_width="40px"
android:layout_height="40px"
android:text="@string/str_button2"
android:textSize="20sp"
android:layout_x="277px"
android:layout_y="55px"
>
</Button>
<!-- 建立第三个Button
-->
<Button
android:id="@+id/myButton3"
android:layout_width="40px"
android:layout_height="40px"
android:text="@string/str_button3"
android:textSize="20sp"
android:layout_x="240px"
android:layout_y="55px"
>
</Button>
<!-- 建立第一个ToggleButton
-->
<ToggleButton
android:id="@+id/myButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="@string/str_button5"
android:textOn="@string/str_button6"
android:layout_x="30px"
android:layout_y="92px"
></ToggleButton>
<!-- 建立第三个TextView
-->
<TextView
android:id="@+id/myText3"
android:layout_width="200sp"
android:layout_height="50sp"
android:text="欢迎使用"
android:textSize="10sp"
android:padding="12dip"
android:background="#FFE4C4"
android:textColor="#0000CD"
android:layout_x="125px"
android:layout_y="92px"
></TextView>
<!-- Google MapView Widget -->
<com.google.android.maps.MapView
android:id="@+id/myMapView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_x="0px"
android:layout_y="142px"
android:enabled="true"
android:clickable="true"
android:apiKey="0msHaq9AU6OJwZR3mN1DstI-wNKx9p4Yio_bncQ"
>
</com.google.android.maps.MapView>
</AbsoluteLayout>
2.第二部分,位置解析功能代码实现
编写PositionConvert.java:
package com.sharpandroid.navigation;
/* import相关class */
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
public class PositionConvert extends MapActivity
{
private MapController mapController;
private MapView mapView;
private Button Button01,Button02,Button03;
private ToggleButton Button4;
private EditText EditText01;
private EditText EditText02;
private TextView textView;
private int intZoomLevel;
/* Map启动时的默认坐标:八达岭长城 */
private double dLat=40.362643;
private double dLng=116.019793;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.resolve);
/* 创建MapView对象 */
mapView = (MapView)findViewById(R.id.myMapView1);
/*通过MapView对象得到mapView的控制器*/
mapController = mapView.getController();
/*将默认位置定位到地图上*/
GeoPoint geoPoint = new GeoPoint((int)(dLat*1E6), (int)(dLng*1E6));
mapController.animateTo(geoPoint);
/* 设置MapView的显示选项(卫星、街道) */
mapView.setSatellite(false);
mapView.setStreetView(true);
/* 默认放大的层级 */
intZoomLevel = 17;
/*设值mapView此时的放大级别*/
mapController.setZoom(intZoomLevel);
/*得到显示地址详细信息的TextView控件*/
textView = (TextView) this.findViewById(R.id.myText3);
/* 更新MapView*/
refreshMapView();
/* 得到查询的EditText控件 */
EditText01 = (EditText)findViewById(R.id.myEdit1);
EditText02 = (EditText)findViewById(R.id.myEdit2);
/* 得到查询的Button控件 */
Button01 = (Button)findViewById(R.id.myButton1);
Button01.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v)
{
/* 经纬度空白检查 */
if(EditText01.getText().toString().equals("")||
EditText02.getText().toString().equals(""))
{
showDialog("经度或纬度填写不正确!");
}
else
{
/* 取得输入的经纬度 */
dLng=Double.parseDouble(EditText01.getText().toString());
dLat=Double.parseDouble(EditText02.getText().toString());
GeoPoint p = new GeoPoint((int)(dLat* 1E6), (int)(dLng* 1E6));
/*得到坐标定位标示层*/
readPoint rPoint = new readPoint(p);
/*得到MapView中的所有的图层*/
List<Overlay> overlays =mapView.getOverlays();
/*清空MapView中的图层*/
overlays.clear();
/*将图标的图层加到MapView的图层中*/
overlays.add(rPoint);
/*通过自定义方法得到GeoPoint对应的地址*/
String pa =getAddressbyGeoPoint(p);
/*将得到的内容以Dialog形式显示出来*/
showDialog(pa);
/*将得到的内容以TextView形式显示出来*/
textView.setText(pa);
/*刷新MapView页面*/
refreshMapView();
}
}
});
/* 放大Map的Button */
Button02 = (Button)findViewById(R.id.myButton2);
Button02.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v)
{
intZoomLevel++;
if(intZoomLevel>mapView.getMaxZoomLevel())
{
intZoomLevel = mapView.getMaxZoomLevel();
}
mapController.setZoom(intZoomLevel);
}
});
/* 缩小Map的Button */
Button03 = (Button)findViewById(R.id.myButton3);
Button03.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v)
{
intZoomLevel--;
if(intZoomLevel<1)
{
intZoomLevel = 1;
}
mapController.setZoom(intZoomLevel);
}
});
/*添加卫星试图切换Button*/
Button4 = (ToggleButton) this.findViewById(R.id.myButton4);
Button4.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
if (isChecked == true) {
mapView.setSatellite(true);
}else {
mapView.setSatellite(false);
}
}
});
}
/*添加按键控制*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_A){
mapController.setZoom(intZoomLevel+1);
return true;
}else if (keyCode == KeyEvent.KEYCODE_D) {
mapController.setZoom(intZoomLevel-1);
return true;
}else if (keyCode == KeyEvent.KEYCODE_W) {
mapView.setSatellite(true);
mapView.setTraffic(false);
return true;
}else if (keyCode == KeyEvent.KEYCODE_S) {
mapView.setSatellite(false);
mapView.setTraffic(true);
return true;
}
return false;
}
/*创建MapView的图标层*/
protected class readPoint extends Overlay{
private GeoPoint g;
public readPoint(GeoPoint geo){
super();
g = geo;
}
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
if (shadow == false) {
Projection projection = mapView.getProjection();
Point p = new Point();
projection.toPixels(g, p);
Paint paint = new Paint();
paint.setARGB(255, 255, 0, 0);
paint.setAntiAlias(true);
canvas.drawCircle(p.x, p.y, 5, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
}
/* 刷新Map的method */
public void refreshMapView()
{
GeoPoint gp= new GeoPoint((int)(dLng*1E6),(int)(dLng*1E6));
mapView.displayZoomControls(true);
/* 将Map的中点移至GeoPoint */
mapController.animateTo(gp);
mapController.setZoom(intZoomLevel);
mapView.setTraffic(true);
mapView.setSatellite(false);
}
@Override
protected boolean isRouteDisplayed()
{
return false;
}
/* 显示Dialog的method */
private void showDialog(String mess){
new AlertDialog.Builder(PositionConvert.this).setTitle("Message")
.setMessage(mess)
.setNegativeButton("确定", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
})
.show();
}
public String getAddressbyGeoPoint(GeoPoint gp)
{
String strReturn = "";
try
{
/* 当GeoPoint不等于null */
if (gp != null)
{
/* 创建Geocoder对象 */
Geocoder gc = new Geocoder
(PositionConvert.this, Locale.getDefault());
/* 取出地理坐标经纬度 */
double geoLatitude = (int)gp.getLatitudeE6()/1E6;
double geoLongitude = (int)gp.getLongitudeE6()/1E6;
/* 自经纬度取得地址(可能有多行地址) */
List<Address> lstAddress =
gc.getFromLocation(geoLatitude, geoLongitude, 1);
StringBuilder sb = new StringBuilder();
/* 判断地址是否为多行 */
if (lstAddress.size() > 0)
{
Address adsLocation = lstAddress.get(0);
for(int i=0;i<adsLocation.getMaxAddressLineIndex();i++)
{
sb.append(adsLocation.getAddressLine(i)).append(" ");
}
sb.append(adsLocation.getLocality()).append(" ");
sb.append(adsLocation.getPostalCode()).append(" ");
sb.append(adsLocation.getCountryName());
}
/*
* 将获取到的地址
* 组合后放在StringBuilder对象中输出用
*/
strReturn = sb.toString();
}
}
catch(Exception e)
{
e.printStackTrace();
}
return strReturn;
}
}
3.第三部分,实现两地理位置在MapView上路径导航
编写DirectionTracks.java:
package com.sharpandroid.navigation;
import java.util.List;
import java.util.Locale;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DirectionTracks extends MapActivity {
private MapView mapView;
private MapController mapController;
private TextView textView;
private EditText editText;
private int intzoomlevel;
private Location mlocation = null;
private LocationManager locationManager;
private String strLocationPrivider = "";
private GeoPoint fromGeoPoint ,toGeoPoint;
private Button button1;
private Button button2;
private Button button3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation);
/*得到*/
textView = (TextView) this.findViewById(R.id.myTextView1);
/*得到输入目的地址的EditText控件*/
editText = (EditText) this.findViewById(R.id.myEditText1);
/*在editText中得到默认的地址*/
editText.setText(getResources().getText(R.string.str_default_
address).toString());
/*创建MapView对象*/
mapView = (MapView) this.findViewById(R.id.myMapView1);
/*通过MapView对象得到mapView的控制器*/
mapController = mapView.getController();
/* 设置MapView的显示选项(卫星、街道) */
mapView.setTraffic(true);
mapView.setSatellite(false);
mapView.setStreetView(true);
/* 默认放大的层级 */
intzoomlevel = 15;
/*设值mapView此时的放大级别*/
mapController.setZoom(intzoomlevel);
/*通过系统服务得到定位服务管理器*/
locationManager = (LocationManager) getSystemService
(Context.LOCATION_SERVICE);
/*得到定位提供者*/
getLocationProvider();
/*得到当前位置即出发位置 */
fromGeoPoint = getGeoByLocation(mlocation);
/*实时更新MapView*/
refreshMapViewByGeoPoint(fromGeoPoint, mapView, intzoomlevel);
/*更新位置状态*/
locationManager.requestLocationUpdates(strLocationPrivider, 2000,
10, listener);
/*触发导航事件*/
button1 = (Button) this.findViewById(R.id.myButton1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(editText.getText().toString()!=null){
toGeoPoint = getGeoByAddress(editText.getText().
toString());
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(
Uri.parse("http://maps.google.com/maps?f=d&saddr=
"+geoPointToString(fromGeoPoint)+
"&daddr="+geoPointToString(toGeoPoint)+"&h1=cn")
);
startActivity(intent);
}
}
});
/* 放大Map的Button */
button2 = (Button) this.findViewById(R.id.myButton2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intzoomlevel ++;
if (intzoomlevel > mapView.getMaxZoomLevel()) {
intzoomlevel = mapView.getMaxZoomLevel();
}
mapController.setZoom(intzoomlevel);
}
});
/* 缩小Map的Button */
button3 = (Button) this.findViewById(R.id.myButton3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intzoomlevel --;
if (intzoomlevel < 1) {
intzoomlevel = 1;
}
mapController.setZoom(intzoomlevel);
}
});
}
/**
*
* 将 geopoint里的经纬度以“String ,String”返回
* @param gp
* @return
*/
private String geoPointToString(GeoPoint gp){
String strturn ="";
try {
if(gp!=null){
double geoLatitude = (int)gp.getLatitudeE6()/1E6;
double geoLongitude = (int)gp.getLongitudeE6()/1E6;
strturn = String.valueOf(geoLatitude)+","+String.valueOf
(geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return strturn;
}
/**
* 传入geopoint更新mapview里的google map
* @param geoPoint
* @param mapView
* @param zoomLevel
*/
public void refreshMapViewByGeoPoint
(GeoPoint geoPoint ,MapView mapView ,int zoomLevel){
try {
mapView.displayZoomControls(true);
mapController = mapView.getController();
mapController.animateTo(geoPoint);
mapController.setZoom(zoomLevel);
mapView.setSatellite(false);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* 通过文本框输入的地址得到其经纬度坐标
* @param strSearchAddress
* @return
*/
private GeoPoint getGeoByAddress(String strSearchAddress){
GeoPoint gp = null;
try {
if(strSearchAddress != null){
Geocoder geocoder = new Geocoder
(DirectionTracks.this,Locale.getDefault());
List<Address> listAddresses = geocoder.
getFromLocationName
(strSearchAddress, 1);
if(!listAddresses.isEmpty()){
Address addressLocation = listAddresses.get(0);
double geolatitude = addressLocation.
getLatitude()*1E6;
double geolongitude = addressLocation.
getLongitude()*1E6;
gp = new GeoPoint((int)geolatitude, (int)
geolongitude);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}
/**
* 得到当手机GPS坐标更新时的事件
*/
public LocationListener listener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle
extras) {
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
mlocation= location;
fromGeoPoint = getGeoByLocation(location);
refreshMapViewByGeoPoint(fromGeoPoint, mapView, intzoomlevel);
}
};
/**
* 传入location对象,取回其GeoPoint对象
* @param location
* @return
*/
private GeoPoint getGeoByLocation(Location location){
GeoPoint geoPoint =null;
try {
if (location != null) {
double geoLatitude = location.getLatitude()*1E6;
double geoLongitude = location.getLongitude()*1E6;
geoPoint = new GeoPoint((int)geoLatitude,
(int)geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return geoPoint;
}
/**
* 取得LocationProvider
*/
public void getLocationProvider(){
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setSpeedRequired(true);
strLocationPrivider = locationManager.getBestProvider
(criteria, true);
mlocation = locationManager.getLastKnownLocation
(strLocationPrivider);
} catch (Exception e) {
textView.setText(e.toString());
e.printStackTrace();
}
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
4.第四部分,功能整合
编写TravelTracks.java:
package com.sharpandroid.navigation;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class TravelTracks extends Activity {
private Button button1;
private Button button2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button) this.findViewById(R.id.Resolvebutton);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent (TravelTracks.this,
PositionConvert.class);
startActivity(intent);
}
});
button2 = (Button) this.findViewById(R.id.NavigationButton);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(TravelTracks.this,
DirectionTracks.class);
startActivity(intent);
}
});
}
}