几行代码实现Android 地图选择,地址选择,坐标选择

效果图

370502857120419994.jpg
584028419681845739.jpg

准备工作

在腾讯地图控制台里注册一个app,替换下面的参数

主要代码

布局

<?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=".activity.MapSelectionActivity">
    <include layout="@layout/nav_bar" />
    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

逻辑

切记别忘了申请定位权

String mUrl = "https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=0&backurl=http://callback&key=你注册的app的key&referer=你注册的app的名字";
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);
    }
});
mWebView.getSettings().setGeolocationDatabasePath( MapSelectionActivity.this.getFilesDir().getPath() );
mWebView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (!url.startsWith("http://callback")) {
            view.loadUrl(url);
        } else {
            try {
                //转utf-8编码
                String decode = URLDecoder.decode(url, "UTF-8");
                //转uri,然后根据key取值
                Uri uri = Uri.parse(decode);

                String[] latng=uri.getQueryParameter("latng").split(",");
                String address = uri.getQueryParameter("name");//地址
                if (address.equals("我的位置")){
                    address = uri.getQueryParameter("addr");
                }
                Intent intent = new Intent();//把数据返回到上个页面
                intent.putExtra("address", address);
                intent.putExtra("latitude",latng[0]);
                intent.putExtra("longitude",latng[1]);
                setResult(RESULT_OK, intent);
                finish();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
});
mWebView.loadUrl(mUrl);

有疑问请私信我的gzh:急递客
获取上百套项目源码 gzh回复:Android项目

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容