调用网页百度地图进行路径规划

绿豆饼 2020-04-26

参考链接:https://blog.csdn.net/tianxintiandisheng/article/details/81870710

该Demo里有其他的多余功能,可自行删减。

运行效果图(运行前要开启GPS权限):点击保存按钮将会把编辑框里的地址保存到数据库

调用网页百度地图进行路径规划                     调用网页百度地图进行路径规划

目录结构图:

调用网页百度地图进行路径规划

manifest:以下的权限并非都是必要的
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mingrisoft.routeplanning5">

    //获取设备网络状态,禁用后无法获取网络状态
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    //网络权限,当禁用后,无法进行检索等相关业务
    <uses-permission android:name="android.permission.INTERNET" />
    //读取设备硬件信息,统计数据
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    //读取系统信息,包含系统版本等信息,用作统计
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
    //获取设备的网络状态,鉴权所需网络代理
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    //允许sd卡写权限,需写入地图数据,禁用后无法显示地图
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    //允许sd卡读权限,需读取地图数据,禁用后无法显示地图
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    //获取统计数据
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    //鉴权所需该权限获取进程列表
    <uses-permission android:name="android.permission.GET_TASKS" />
    //使用步行AR导航,配置Camera权限
    <uses-permission android:name="android.permission.CAMERA" />
    //网络定位
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    //GPS定位
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">

        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="gEnaDhNCFNRRCKmc7XPM1PttGalSkeKr"/>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ToThere"></activity>
    </application>

</manifest>
DBHospital:
package com.mingrisoft.routeplanning5;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;
import android.util.Log;

public class DBHospital extends SQLiteOpenHelper {
    //用数据库保存目的地,app重启后可从数据库中读取到上次的目的地
    String createHospital = "create table tb_hospital (_id integer primary key autoincrement," +
            "hospital)";

    public DBHospital(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(createHospital);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        Log.i("社区卫生中心地址表","版本更新" + oldVersion + "-->" + newVersion);
    }
}
MainActivity:
package com.mingrisoft.routeplanning5;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private DBHospital dbHospital;
    Button btn_hc_saveAddress;
    Button toThere;
    EditText et_hc_address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_hc_saveAddress = findViewById(R.id.btn_hc_saveAddress);
        et_hc_address = findViewById(R.id.ed_hc_address);
        toThere = findViewById(R.id.btn_hc_toThere);

        dbHospital = new DBHospital(MainActivity.this,"db_hospital",null,1);
        Cursor cursor = dbHospital.getReadableDatabase().query("tb_hospital",null,null, null, null,null,null);

        //读取上次的目的地显示在编辑框中
        if (cursor.getCount() == 0) {
            et_hc_address.setHint("记录为空,可添加社区卫生服务中心地址!");
        } else {
            while (cursor.moveToNext()) {
                et_hc_address.setText(cursor.getString(1));
            }
        }

        //更改并保存新的目的地到数据库
        btn_hc_saveAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_hc_address.getText().toString().equals("")) {
                    Toast.makeText(MainActivity.this, "内容为空!", Toast.LENGTH_SHORT).show();
                } else {
                    dbHospital.getReadableDatabase().delete("tb_hospital", null, null);
                    insertData(dbHospital.getReadableDatabase(), et_hc_address.getText().toString());
                    Toast.makeText(MainActivity.this, "名称(地址)更改成功!", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //规划路线
        toThere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String destination = et_hc_address.getText().toString();

                if (destination.equals("")) {
                    Toast.makeText(MainActivity.this, "内容为空,无法规划路线!", Toast.LENGTH_SHORT).show();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putCharSequence("destination", destination);
                    Intent intent = new Intent(MainActivity.this, ToThere.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        });
    }

    private void insertData(SQLiteDatabase sqLiteDatabase, String hospital) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("hospital", hospital);
        sqLiteDatabase.insert("tb_hospital",null,contentValues);
    }
}
ToThere:
package com.mingrisoft.routeplanning5;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.List;

public class ToThere extends Activity {
    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_there);

        //获取系统的LocationManager对象
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        //添加权限检查
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        //设置每一秒获取一次location信息
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,      //GPS定位提供者
                1000,       //更新数据时间为1秒
                1,      //位置间隔为1米
                //位置监听器
                new LocationListener() {  //GPS定位信息发生改变时触发,用于更新位置信息

                    @Override
                    public void onLocationChanged(Location location) {
                        //GPS信息发生改变时,更新位置
                        locationUpdates(location);
                    }

                    @Override
                    //位置状态发生改变时触发
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                    }

                    @Override
                    //定位提供者启动时触发
                    public void onProviderEnabled(String provider) {
                    }

                    @Override
                    //定位提供者关闭时触发
                    public void onProviderDisabled(String provider) {
                    }
                });
        //从GPS获取最新的定位信息
        //如果只有getLastKnownLocation()没有requestLocationUpdates很可能location为空,所以最好实现requestLocationUpdates()
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        locationUpdates(location);    //将最新的定位信息传递给创建的locationUpdates()方法中
    }

    public void locationUpdates(Location location) {  //获取指定的查询信息
        //如果location不为空时
        if (location != null) {
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            String destination = bundle.getString("destination");
            String start =location.getLatitude() + "," + location.getLongitude();//起点经纬度

            //设置全屏显示
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            WebView webView = (WebView) findViewById(R.id.wv_hc);       //获取布局管理器中添加的WebView组件
            webView.getSettings().setUseWideViewPort(true);    //设置此属性,可任意比例缩放
            webView.getSettings().setLoadWithOverviewMode(true); //设置加载内容自适应屏幕
            //使WebView组件具有放大和缩小网页的功能
            webView.getSettings().setSupportZoom(true);
            webView.getSettings().setBuiltInZoomControls(true);
            Log.i("dddddddd", start);
            //调用网页百度地图进行路径规划,如果精度不够可能得开启浏览器定位权限
            webView.loadUrl("http://api.map.baidu.com/direction?origin=latlng:" + start +
                    "|name:我的位置&destination=" + destination +
                    "&mode=driving&region=南宁&output=html&src=webapp.baidu.openAPIdemo");//指定要加载的网页
        } else {
            Toast.makeText(ToThere.this, "无法获取定位信息!请移动", Toast.LENGTH_SHORT).show();
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="社区卫生服务中心名称(地址):"/>

    <EditText
        android:id="@+id/ed_hc_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btn_hc_saveAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="点击保存"/>

        <Button
            android:id="@+id/btn_hc_toThere"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="点击规划路线"/>

    </LinearLayout>

</LinearLayout>

activity_to_there.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ToThere">

    <WebView
        android:id="@+id/wv_hc"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

相关推荐