【关键字】

webview 地图 高德 腾讯地图 百度地图

【问题背景】

开发元服务过程中需要用到地图能力:卡片中显示我的快递位置和我的位置信息;PageAbility中可以打开自定义地图,查询POI点,做路径规划、路径推荐等;查看了高德、百度、华为、腾信地图的后发现,各大厂商对鸿蒙系统的支持能力参差不齐,都没有提供鸿蒙可用的SDK;于是考虑使用JS API的方式。最初思路被局限在通过鸿蒙的JS 集成地图的JS API,但是最终被各种报错折磨到放弃。

无意中发现WebView这个好东西,他不仅仅是一个view组件,还是可以让我们调用JS的各种方法;

【准备工作】

参照地图厂商的JS API开发指导,申请地图key(这里以高德为例);

cke_382.png

【实现过程】

下面就看下如果通过WebView实现地图能力:

  1. 参照WebView组件初始化指导,千万不要跳过,认真看完指导

    https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-java-component-webview-0000001092715158

    关键步骤一:配置应用的网络权限(没有网你还想调JS API)。

    打开“entry > src > main > config.json”,并添加如下配置。

    "module": {
    "reqPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }]
    }
  2. 新建资源文件:

    cke_20957.png

    资源类型选择:Layout

    cke_27044.png

    布局文件内容中定义地图组件:

    <?xml version="1.0" encoding="utf-8"?>
    <DirectionalLayout
        xmlns:ohos="http://schemas.huawei.com/res/ohos"
        ohos:height="match_parent"
        ohos:width="match_parent"
        ohos:orientation="vertical">
            <ohos.agp.components.webengine.WebView
                ohos:id="$+id:ability_main_webview"
                ohos:height="600vp"
                ohos:width="match_parent"
                ohos:weight="1"/>
            <Text
                ohos:height="150vp"
                ohos:width="match_parent"
                ohos:text="hello map">
            </Text>
    </DirectionalLayout>
  3. 我这边主体页面都是用的JS类Web开发范式开发的,所以需要从JS页面跳转到JAVA页面;使用了一下startAbility跳转到mapAbility。

    新建mapAbility

    cke_37325.png

    cke_40663.png

    Intent intent = new Intent();
    Operation operation = new Intent.OperationBuilder()
            .withBundleName("com.huawei.testjsmap.hmservice")
            .withAbilityName("com.huawei.testjsmap.mapAbility")
            .build();
    intent.setOperation(operation);
    startAbility(intent);
  4. 关键步骤二:Webview调用JS API

    1)允许Webview执行Java Script:webView.getWebConfig().setJavaScriptPermit(true);

    2)加载一个空页面: webView.load("about:blank"); 不要问为什么,问就是没有页面执行个锤子的script。

    3)加载组件:String innhtml="document.getElementsByTagName('html')[0].innerHTML='"+mapbody+"';";

    4)通过document.body.appendChild加载script;直接用innerHTML赋值会导致script加载失败;

    完整代码如下:

    private String mapbody = "<head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no, width=device-width\"><link rel=\"stylesheet\" href=\"https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css\"/><text id=\"maptitle\">地图显示</text><button onclick=\"a()\">try</button><style>html,body,#container {width: 100%;height: 100%;}</style></head><body ><div id=\"container\"></div></body>";
    private String mapfun ="function a(){ document.getElementById(\"maptitle\").innerHTML = \"我的一段 JavaScript代码\";     var map = new AMap.Map(\"container\", { viewMode: \"2D\",zoom:11,center: [116.397428, 39.90923]})};";
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_map_main);
        WebView webView = (WebView) findComponentById(ResourceTable.Id_ability_main_webview);
        webView.getWebConfig().setJavaScriptPermit(true);
        webView.setWebAgent(new WebAgent() {
            @Override
            public void onPageLoaded(WebView webView, String url) {
                String innhtml="document.getElementsByTagName('html')[0].innerHTML='"+mapbody+"';";
                innhtml += "var newscript = document.createElement(\"script\");" ;
                innhtml += " newscript.src=\"https://webapi.amap.com/maps?v=2.0&key=准备工作中申请的地图KEY\";";
                innhtml += "document.body.appendChild(newscript);";
                innhtml += "var functionscript = document.createElement(\"script\");" ;
                innhtml += " functionscript.innerHTML='"+mapfun +"';";
                innhtml += "document.body.appendChild(functionscript);";
                System.out.println("onPageLoaded start:"+innhtml);
                webView.executeJs(innhtml,null);            }
        });
        webView.load("about:blank");

看到这里已经无需多言了,剩下的要在地图上实现哪些业务就看地图JS API能支持哪些能力了。

最后安利一个鸿蒙webview的调试方法

调试开关打开:MainAbility的onstart方法中执行

public void onStart(Intent intent) {
    super.onStart(intent);
    try {
        Class web =  Class.forName("android.webkit.WebView");
        if(web != null){
            Method method = web.getMethod("setWebContentsDebuggingEnabled",boolean.class);
            method.invoke(web,true);
        }
    } catch (ClassNotFoundException | NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

调试工具使用:大家可以自己去百度下webview调试工具,其使用方法一致的。

 欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐