本文介绍了无法实现可视化:地理分布图中的Andr​​oid的WebView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现可视化:地理分布图在Android的web视图

有关可视化:地理分布图,我指developers.google.com /图表/互动/文档/画廊/地理分布图

在这里,我已经实现了第一个例子,在地图上显示的区域。在当我触摸特定区域的Andr​​oid的WebView它显示了国名弹出,因为我触摸地图之外的地区它显示了同样的弹出窗口。

问题:在机器人的WebView,当我接触外面谷歌地图弹出窗口不会消失。它应该工作同样作为桌面上的web浏览器

桌面版:

我创建了桌面demo.html文件。它在Web浏览器中正常运行。

 < HTML和GT;
  < HEAD>
    <脚本类型=文/ JavaScript的SRC =htt​​ps://www.google.com/jsapi>< / SCRIPT>
    <脚本类型=文/ JavaScript的>
      的google.load(可视化,1,{包:[地理分布图]});
      google.setOnLoadCallback(drawMap);      功能drawMap(){
        VAR数据= google.visualization.arrayToDataTable([
          ['国家','流行'],
          ['德',200]
          ['美国',300]
          ['巴西',400]
          ['加拿大',500]
          ['法国',600]
          [RU,700]
        ]);        VAR的选择= {};
        选项​​['数据模式'] ='区';        变种容器=的document.getElementById('regions_div');
        VAR地理位置图=新google.visualization.GeoMap(容器);        geomap.draw(数据,选项);
      };
    < / SCRIPT>
  < /头>
  <身体GT;
    < D​​IV ID =regions_div的风格=WIDTH:900px;高度:500像素;>< / DIV>
  < /身体GT;
< / HTML>

Android版本:

 进口android.annotation.TargetApi;
进口android.content.Context;
进口android.os.Build;
进口android.os.Bundle;
进口android.support.v7.app.ActionBarActivity;
进口android.util.Log;
进口android.view.Display;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.view.WindowManager;
进口android.webkit.WebChromeClient;
进口android.webkit.WebView;
进口android.widget.Toast;公共类WebActivity扩展ActionBarActivity {    web视图的WebView;
    StringBuilder的构建=新的StringBuilder();    @TargetApi(Build.VERSION_ codeS.HONEYCOMB)
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_web);        web视图=(的WebView)findViewById(R.id.webView1);        webView.getSettings()setJavaScriptEnabled(真)。
        。webView.getSettings()setBuiltInZoomControls(真);
        。webView.getSettings()setUseWideViewPort(真);
        。webView.getSettings()setLoadWithOverviewMode(真);        INT currentapiVersion = android.os.Build.VERSION.SDK_INT;
        如果(currentapiVersion> = android.os.Build.VERSION_ codeS.HONEYCOMB)
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE,NULL);        webView.setInitialScale(的getScale());        webView.setWebChromeClient(新WebChromeClient());        build.append(['德',200]);
        build.append([美国,700]);
        build.append(['巴西',300]);
        build.append([加拿大,400]);
        build.append(['法国',500]);        drawMap();
        //webView.loadUrl(\"http://www.stalwarttech.net/dummy/demo3.html);    }    无效drawMap()
    {
        如果(build.length()大于0)
        {
            字符串JS =< HTML和GT;< HEAD>中+
                    <脚本类型='+文/ JavaScript的+'SRC ='+https://www.google.com/jsapi+'>< / SCRIPT>中+
                    <脚本类型='+文/ JavaScript的+>中+
                    的google.load('+可视化+,+1+,{包:['+geochart+']}); +
                    google.setOnLoadCallback(drawRegionsMap); +
                    功能drawRegionsMap(){+
                    VAR数据= google.visualization.arrayToDataTable([+
                    ['国家','流行'],+ +建
                    ]); +
                    VAR选项= {颜色:['#CB96CE','#871F7B']}; +
                    无功表=新google.visualization.GeoChart(的document.getElementById('regions_div')); +
                    chart.draw(数据,选项); +
                    }+
                    &所述; /脚本>中+
                    < /头>中+
                    <身体GT; +
                    < D​​IV ID ='+regions_div+'风格='+宽度:100%;身高:100%;+'>< / DIV>中+
                    < /身体GT; +
                    < / HTML>中;            Log.d(标签,JS);            webView.loadDataWithBaseURL(文件:/// android_asset /,JS,text / html的,UTF-8,NULL);
        }
        其他
        {
            Toast.makeText(这一点,没有找到数据,Toast.LENGTH_LONG).show();
        }    }    私人诠释的getScale(){
        显示显示=((窗口管理器)getSystemService(Context.WINDOW_SERVICE))getDefaultDisplay()。
        INT宽度= display.getWidth();
        双VAL =新的双(宽)/双新(800);
        VAL = VAL * 100D;        返回val.intValue();
    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        //充气菜单;如果是present这增加了项目操作栏。
        。getMenuInflater()膨胀(R.menu.web,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        //处理动作栏项目点击这里。操作栏会
        //自动处理上点击主页/向上按钮,只要
        //你在AndroidManifest.xml中指定一个父活动。
        INT ID = item.getItemId();
        如果(ID == R.id.action_settings){
            返回true;
        }
        返回super.onOptionsItemSelected(项目);
    }
}


解决方案

所有的平台支持

所有你需要做的就是创造的.html文件编程并存储HTML内容到该文件,然后在该文件的绝对地址的WebView打开相同的文件......就这么简单:)

在这里你去,开箱即用

私人无效loadWorldMap(){
        尝试{

 字符串的HTMLDocument =<!DOCTYPE HTML PUBLIC \\ -  // W3C // DTD XHTML 1.0过渡// EN \\\\http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd\\\">\
+
                < HTML的xmlns = \\HTTP://www.w3.org/1999/xhtml \\>< HEAD>< META HTTP-当量= \\内容类型\\的内容= \\text / html的,宽度=设备宽度,用户可扩展= YES;字符集=窗口1252 \\> \\ n+
                <脚本类型= \\文/ JavaScript的\\SRC = \\HTTPS://www.google.com/jsapi \\>< / SCRIPT> \\ n+
                <脚本类型= \\文/ JavaScript的\\> \\ n+
                的google.load('可视化','1',{'包':['geochart']}); \\ N+
                google.setOnLoadCallback(drawRegionsMap); \\ n+
                \\ n+
                功能drawRegionsMap(){\\ n+
                VAR数据= google.visualization.arrayToDataTable([\\ n+
                ['国家',''],\\ n                //添加你的城市数据缓冲区[国家列表])                +构建+
                ]); \\ n+
                \\ n+
                VAR选项= {}; \\ n+
                \\ t \\ toptions = {\\ n+
                datalessRegionColor:#29ABE2',\\ n+
                \\ t \\ t \\ t \\ t的backgroundColor:'#F3F3F3,\\ n+
                \\ t \\ t \\ t \\ t \\ tcolorAxis:{颜色:['#0071BC']} \\ n+
                keepAspectRatio:假的,\\ n+
                传说:假的,\\ n+
                提示:{TEXTSTYLE:{颜色:#0099CB'的fontName:'宋体',字体:'10'}} \\ n+
                }; \\ n+
                \\ t \\ t \\ n+
                无功表=新google.visualization.GeoChart(的document.getElementById('chart_div')); \\ n+
                chart.draw(数据,选项); \\ n+
                }; \\ n+
                < / SCRIPT> \\ n+
                < /头> \\ n+
                <身体GT; \\ n+
                < D​​IV ID = \\chart_div \\的风格= \\宽度:100%;身高:100%; \\>< D​​IV的风格= \\位置:亲属; \\>< D​​IV DIR = \\升\\的风格= \\的位置是:相对的;宽度:100%;身高:100%; \\>< D​​IV的风格= \\的立场:绝对的;左:0像素;顶:0像素;宽度:100%;身高:100%; \\>< / DIV>< / DIV>< / DIV>< / DIV> \\ n+
                \\ n+
                < /身体GT;< / HTML>中;
        //创建中的主要外部存储空间的跟踪文件
        //当前应用程序。
        //如果文件不存在,则创建它。        文件TRACEFILE =新的文件((本).getCacheDir(),TraceFile.html);
        如果(!traceFile.exists())
            traceFile.createNewFile();
        //添加一行以跟踪文件
        但是BufferedWriter作家=新的BufferedWriter(新的FileWriter(跟踪文件,虚假/ * *追加/));
        writer.write(HTMLDocument的);
        writer.close();
        MediaScannerConnection.scanFile(getApplicationContext(),
                新的String [] {traceFile.toString()},
                空值,
                空值);
        Log.d(文件创建,成功);
        Log.d(绝对路径,traceFile.getAbsolutePath());
        absoluteDir = traceFile.getAbsolutePath();         //加载的世界地图
        mapView.getSettings()setDefaultZoom(WebSettings.ZoomDensity.FAR)。        mapView.getSettings()setJavaScriptEnabled(真)。
        。mapView.getSettings()setBuiltInZoomControls(假);
        。mapView.getSettings()setUseWideViewPort(真);
        mapView.requestFocusFromTouch();
        mapView.requestFocus(View.FOCUS_DOWN);
        。mapView.getSettings()setLoadWithOverviewMode(真);        //webView.setWebViewClient(new WebViewClient());
        mapView.setWebChromeClient(新WebChromeClient(){
            公共无效onProgressChanged(的WebView观点,诠释进度){
                llLoadingMap.setVisibility(View.VISIBLE);
                如果(==进度100)
                    llLoadingMap.setVisibility(View.GONE);
            }
        });        mapView.loadUrl(文件:///+ absoluteDir);
        。mapView.getSettings()setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        INT屏幕宽度= getWindowManager()
                。.getDefaultDisplay()的getWidth();
        mapView.setLayoutParams(新LinearLayout.LayoutParams(
                屏幕宽度,LinearLayout.LayoutParams.MATCH_PARENT,1F));
    }赶上(IOException异常五){
        Log.e(错误文件,无法写入TraceFile.html文件。);
    }}

I am trying to implement Visualization: Geomap in android Webview.

For Visualization:Geomap, I refer developers.google.com /chart/interactive/docs/gallery/geomap

Here I have implemented first example to show regions on map. In android webview when I touch on specific region it shows the popup with country name, as I touch outside region of map it shows the same popup.

ISSUE: In android webview , popup doesn’t disappear when I touch outside Google map. It should work similarly as on desktop web browser

DESKTOP VERSION:

I created demo.html file on desktop . Its running properly in web browser .

    <html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["geomap"]});
      google.setOnLoadCallback(drawMap);

      function drawMap() {
        var data = google.visualization.arrayToDataTable([
          ['Country', 'Popularity'],
          ['Germany', 200],
          ['United States', 300],
          ['Brazil', 400],
          ['Canada', 500],
          ['France', 600],
          ['RU', 700]
        ]);

        var options = {};
        options['dataMode'] = 'regions';

        var container = document.getElementById('regions_div');
        var geomap = new google.visualization.GeoMap(container);

        geomap.draw(data, options);
      };
    </script>
  </head>
  <body>
    <div id="regions_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

ANDROID VERSION:

DOWNLOAD APP

http://i62.tinypic.com/edb9w.jpg

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

public class WebActivity extends ActionBarActivity {

    WebView webView;
    StringBuilder build = new  StringBuilder();

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        webView=(WebView)findViewById(R.id.webView1);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB)
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE,null);

        webView.setInitialScale(getScale());

        webView.setWebChromeClient(new WebChromeClient());

        build.append("['Germany', 200],");
        build.append("['United States', 700],");
        build.append("['Brazil', 300],");
        build.append("['Canada', 400],");
        build.append("['France', 500]");

        drawMap();
        //webView.loadUrl("http://www.stalwarttech.net/dummy/demo3.html");

    }



    void drawMap()
    {
        if(build.length() > 0)
        {
            String js = "<html><head>" +
                    "<script type='"+"text/javascript"+"' src='"+"https://www.google.com/jsapi"+"'></script>"+
                    "<script type='"+"text/javascript"+"'>" +
                    "google.load('"+"visualization"+"', '"+"1"+"', {packages:['"+"geochart"+"']});" +
                    "google.setOnLoadCallback(drawRegionsMap);" +
                    " function drawRegionsMap() {" +
                    "  var data = google.visualization.arrayToDataTable([" +
                    "['Country', 'Popularity']," + build +
                    "]);" +
                    "var options = {colors: ['#CB96CE', '#871F7B']};" +
                    "var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));" +
                    "chart.draw(data, options);" +
                    "}" +
                    "</script>" +
                    "</head>" +
                    "<body>" +
                    "<div id='"+"regions_div"+"' style='"+"width:100%; height: 100%;"+"'></div>" +
                    "</body>" +
                    "</html>";

            Log.d("tag",js);

            webView.loadDataWithBaseURL("file:///android_asset/", js, "text/html","UTF-8",  null);
        }
        else
        {
            Toast.makeText(this, "No data found", Toast.LENGTH_LONG).show();
        }

    }

    private int getScale(){
        Display display=((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int width=display.getWidth();
        Double val=new Double(width)/new Double(800);
        val=val*100d;

        return val.intValue();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.web, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
解决方案

ALL PLATFORM SUPPORT

All what you need to do is just create ".html" file programmatically and store the html content into that file then open the same file in webview with absolute address of that file ... simple as that :)

here you go, out of the box

private void loadWorldMap() { try {

        String htmlDocument = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
                "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html,width=device-width,user-scalable=yes; charset=windows-1252\">\n" +
                "    <script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\n" +
                "    <script type=\"text/javascript\">\n" +
                "     google.load('visualization', '1', {'packages': ['geochart']});\n" +
                "     google.setOnLoadCallback(drawRegionsMap);\n" +
                "\n" +
                "      function drawRegionsMap() {\n" +
                "        var data = google.visualization.arrayToDataTable([\n" +
                "          ['Country', ''],\n"

                //add your city data buffer [List of countries] ;)

                + build +


                "        ]);\n" +
                "\n" +
                "        var options = {};\n" +
                "\t\toptions = { \n" +
                "                    datalessRegionColor: '#29ABE2',\n" +
                "\t\t\t\t    backgroundColor: '#F3F3F3',\n" +
                "\t\t\t\t\tcolorAxis: {colors: ['#0071BC']},\n" +
                "                    keepAspectRatio: false,                    \n" +
                "                    legend: false,\n" +
                "                    tooltip: { textStyle: { color: '#0099CB', fontName: 'Arial', fontSize: '10'} }\n" +
                "                };\n" +
                "\t\t\n" +
                "        var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));\n" +
                "        chart.draw(data, options);\n" +
                "    };\n" +
                "    </script>\n" +
                "  </head>\n" +
                "  <body>\n" +
                "  <div id=\"chart_div\" style=\"width: 100%; height: 100%;\"><div style=\"position: relative;\"><div dir=\"ltr\" style=\"position: relative; width: 100%; height: 100%;\"><div style=\"position: absolute; left: 0px; top: 0px; width: 100%; height: 100%;\"></div></div></div></div>\n" +
                "  \n" +
                "</body></html>";


        // Creates a trace file in the primary external storage space of the
        // current application.
        // If the file does not exists, it is created.

        File traceFile = new File((this).getCacheDir(), "TraceFile.html");
        if (!traceFile.exists())
            traceFile.createNewFile();
        // Adds a line to the trace file
        BufferedWriter writer = new BufferedWriter(new FileWriter(traceFile, false /*append*/));
        writer.write(htmlDocument);
        writer.close();


        MediaScannerConnection.scanFile(getApplicationContext(),
                new String[]{traceFile.toString()},
                null,
                null);
        Log.d("file created", "Success.");
        Log.d("absolute path ", traceFile.getAbsolutePath());


        absoluteDir = traceFile.getAbsolutePath();

         // Load world map
        mapView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);

        mapView.getSettings().setJavaScriptEnabled(true);
        mapView.getSettings().setBuiltInZoomControls(false);
        mapView.getSettings().setUseWideViewPort(true);
        mapView.requestFocusFromTouch();
        mapView.requestFocus(View.FOCUS_DOWN);
        mapView.getSettings().setLoadWithOverviewMode(true);

        //webView.setWebViewClient(new WebViewClient());
        mapView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                llLoadingMap.setVisibility(View.VISIBLE);
                if (progress == 100)
                    llLoadingMap.setVisibility(View.GONE);
            }
        });

        mapView.loadUrl("file:///" + absoluteDir);
        mapView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        int screenWidth = getWindowManager()
                .getDefaultDisplay().getWidth();
        mapView.setLayoutParams(new LinearLayout.LayoutParams(
                screenWidth, LinearLayout.LayoutParams.MATCH_PARENT, 1f));


    } catch (IOException e) {
        Log.e("error file", "Unable to write to the TraceFile.html file.");
    }

}

这篇关于无法实现可视化:地理分布图中的Andr​​oid的WebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:58
查看更多