使用phonegap和ol3时的空地图

时间:2015-10-09 06:41:29

标签: android cordova phonegap-build openlayers-3

我正在使用https://github.com/netgis/ol3示例来创建我的地图应用程序。但是当我尝试从phonegap创建.apk文件时,我会在启动时获得空白地图。

应用程序中的My Folder结构在我的应用程序中如下所示:

**APP**
-- css
-- img
-- js
-- config.xml
-- icon.png
-- index.html

我的申请表中有以下代码: 的的index.html

<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/jquery.mobile.min.css" />
<link rel="stylesheet" href="css/ol3.css" type="text/css">
<link rel="stylesheet" href="css/map.css" type="text/css">
<script src="js/cordova-2.4.0.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.mobile.min.js"></script>
<script src="js/ol3.js" ></script>
<script src="js/map.js" ></script>
<script src="js/compass.js" ></script>
<title>OL3 Map</title>
</head>
<body>
<!-- Mappage -->
<div data-role="page" id="mappage" data-theme="c"> 
  <!-- /left panel -->
  <div data-role="panel" data-position="left" data-position-fixed="true" data-display="overlay" data-theme="c" id="nav-panel">
    <ul data-role="listview" data-theme="c" class="nav-search">
      <li data-icon="delete"><a href="#" data-rel="close">Menu</a></li>
    </ul>
    <br>
    <label for="gpsstatus">Watch GPS:</label>
    <select name="gpsstatus" id="gpsstatus" data-role="slider" data-mini="true" >
      <option value="off" selected>Off</option>
      <option value="on">On</option>
    </select>
    <div id="gpsmessage"></div>
    <br>
    <label for="compassstatus">Watch Compass:</label>
    <select data-role="slider" name="compassstatus" id="compassstatus" data-mini="true" >
        <option value="off" selected>Off</option>
        <option value="on">On</option>      
    </select>

    <div id="compassmapstatusdiv">
    <label for="compassmapstatus">Rotate Map:</label>
    <select data-role="slider" name="compassmapstatus" id="compassmapstatus" data-mini="true" >
        <option value="off" selected>Off</option>
        <option value="on">On</option>      
    </select>
    </div>
    <br>
    <fieldset data-role="controlgroup"  data-mini="true" >
      <legend>Layer:</legend>
      <input name="bglayer" id="mapquest" type="radio" value="0" checked>
      <label for="mapquest">OSM MapQuest</label>
      <input name="bglayer" id="osm" type="radio" value="1" >
      <label for="osm">OSM Standard</label>
      <input name="bglayer" id="openaereal" type="radio" value="2" >
      <label for="openaereal">MapQuest Open Aerial</label>
    </fieldset>
  </div>
  <!-- /Ende left panel --> 

  <!-- /info popup -->
    <div data-role="popup" id="popupMenu" data-theme="c" class="ui-corner-all">
    <a href="#" data-rel="back" data-role="button" data-theme="c" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Close</a>
        <div data-role="header" data-theme="c" class="ui-corner-top">
            <h1>Tools</h1>
        </div>
        <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
            <div style="font-size:14px; padding: 12px;" >
                <strong>AppInfos</strong><br>
                Open Source Software:<br>
                OpenLayers r3.0.0-alpha.1<br>
                jQuery mobile 1.3.1<br>
                Phonegap/ Cordova 2.4.0<br><br>             
                Contact:<br>
                Sven Schroeter<br>
                <a href="https://twitter.com/sven_s8" target="_blank">@sven_s8 </a><br><br>
            </div>
        </div>
    </div>
  <!-- /Ende info popup -->

  <!-- /Map page -->
  <div id="head" data-theme="c" data-role="header" data-position="fixed">
    <h3>OL3 Map </h3>
    <a href="#nav-panel" data-icon="bars" class="ui-btn-left">Menu</a> <a href="#popupMenu" data-rel="popup" data-position-to="window" data-role="button" data-inline="true" data-icon="info" data-transition="pop"  data-iconpos="notext" >Info</a> </div>
  <div data-role="content">
    <div id="compassneedle"></div>  
    <div id="map"></div>
  </div>
  <!-- /Ende Map page -->
</div>
</body>
</html>

我的 config.xml 如下所示:

<?xml version="1.0" encoding="UTF-8"?>

<!-- config.xml reference: https://build.phonegap.com/docs/config-xml -->
<widget xmlns     = "http://www.w3.org/ns/widgets"
        xmlns:gap = "http://phonegap.com/ns/1.0"
        id        = "com.phonegap.offlinemapping"
        version   = "1.0.0">

    <name>mobile-ol3</name>

    <description>
        Allows map tiles to be accessed from a local SQL database
    </description>

    <author email="miller.james01@gmail.com">
        Jim Miller
    </author>

    <!--
        Enable individual API permissions here.
        The "device" permission is required for the 'deviceready' event.
    -->
    <feature name="http://api.phonegap.com/1.0/device" />

    <!--
        If you do not want any permissions to be added to your app, add the
        following tag to your config.xml; you will still have the INTERNET
        permission on your app, which PhoneGap requires.
    -->
    <preference name="permissions"                value="none"/>

    <!-- Customize your app and platform with the preference element. -->
    <!-- <preference name="phonegap-version"      value="3.4.0" /> -->      <!-- all: current version of PhoneGap -->
    <preference name="orientation"                value="default" />        <!-- all: default means both landscape and portrait are enabled -->
    <preference name="target-device"              value="universal" />      <!-- all: possible values handset, tablet, or universal -->
    <preference name="fullscreen"                 value="true" />           <!-- all: hides the status bar at the top of the screen -->
    <preference name="webviewbounce"              value="true" />           <!-- ios: control whether the screen 'bounces' when scrolled beyond the top -->
    <preference name="prerendered-icon"           value="true" />           <!-- ios: if icon is prerendered, iOS will not apply it's gloss to the app's icon on the user's home screen -->
    <preference name="stay-in-webview"            value="false" />          <!-- ios: external links should open in the default browser, 'true' would use the webview the app lives in -->
    <preference name="ios-statusbarstyle"         value="black-opaque" />   <!-- ios: black-translucent will appear black because the PhoneGap webview doesn't go beneath the status bar -->
    <preference name="detect-data-types"          value="true" />           <!-- ios: controls whether data types (such as phone no. and dates) are automatically turned into links by the system -->
    <preference name="exit-on-suspend"            value="false" />          <!-- ios: if set to true, app will terminate when home button is pressed -->
    <preference name="show-splash-screen-spinner" value="true" />           <!-- ios: if set to false, the spinner won't appear on the splash screen during app loading -->
    <preference name="auto-hide-splash-screen"    value="true" />           <!-- ios: if set to false, the splash screen must be hidden using a JavaScript API -->
    <preference name="disable-cursor"             value="false" />          <!-- blackberry: prevents a mouse-icon/cursor from being displayed on the app -->
    <preference name="android-minSdkVersion"      value="7" />              <!-- android: MIN SDK version supported on the target device. MAX version is blank by default. -->
    <preference name="android-installLocation"    value="internalOnly" />   <!-- android: app install location. 'auto' will choose. 'internalOnly' is device memory. 'preferExternal' is SDCard. -->
    <preference name="AndroidPersistentFileLocation" value="Internal" />

    <!-- Plugins can also be added here. -->
    <!--
        <gap:plugin name="Example" />
        A list of available plugins are available at https://build.phonegap.com/docs/plugins
    -->

    <!-- Define app icon for each platform. -->
    <icon src="icon.png" />
    <icon src="icon.png"   gap:platform="android"    gap:density="ldpi" />
    <icon src="icon.png"   gap:platform="android"    gap:density="mdpi" />
    <icon src="icon.png"   gap:platform="android"    gap:density="hdpi" />
    <icon src="icon.png"  gap:platform="android"    gap:density="xhdpi" />
    <icon src="icon.png"     gap:platform="blackberry" />
    <icon src="icon.png"     gap:platform="blackberry" gap:state="hover"/>
    <icon src="icon.png"            gap:platform="ios"        width="57" height="57" />
    <icon src="icon.png"            gap:platform="ios"        width="72" height="72" />
    <icon src="icon.png"         gap:platform="ios"        width="114" height="114" />
    <icon src="icon.png"         gap:platform="ios"        width="144" height="144" />
    <icon src="ico.png"          gap:platform="webos" />
    <icon src="icon.png"  gap:platform="winphone" />
    <icon src="icon.png" gap:platform="winphone"   gap:role="background" />

    <!-- Define app splash screen for each platform. -->
    <gap:splash src="res/screen/android/screen-ldpi-portrait.png"  gap:platform="android" gap:density="ldpi" />
    <gap:splash src="res/screen/android/screen-mdpi-portrait.png"  gap:platform="android" gap:density="mdpi" />
    <gap:splash src="res/screen/android/screen-hdpi-portrait.png"  gap:platform="android" gap:density="hdpi" />
    <gap:splash src="res/screen/android/screen-xhdpi-portrait.png" gap:platform="android" gap:density="xhdpi" />
    <gap:splash src="res/screen/blackberry/screen-225.png"         gap:platform="blackberry" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait.png"    gap:platform="ios"     width="320" height="480" />
    <gap:splash src="res/screen/ios/screen-iphone-portrait-2x.png" gap:platform="ios"     width="640" height="960" />
    <gap:splash src="res/screen/ios/screen-ipad-portrait.png"      gap:platform="ios"     width="768" height="1024" />
    <gap:splash src="res/screen/ios/screen-ipad-landscape.png"     gap:platform="ios"     width="1024" height="768" />
    <gap:splash src="res/screen/windows-phone/screen-portrait.jpg" gap:platform="winphone" />

    <gap:plugin name="org.apache.cordova.file" source="npm"/>
    <gap:plugin name="org.apache.cordova.file-transfer" source="npm"/>

    <!--
        Define access to external domains.

        <access />            - a blank access tag denies access to all external resources.
        <access origin="*" /> - a wildcard access tag allows access to all external resource.

        Otherwise, you can specify specific domains:
    -->
    <access origin="http://127.0.0.1*"/><!-- allow local pages -->
    <access origin="*" subdomains="true"/> 
    <!--
        <access origin="http://phonegap.com" />                    - allow any secure requests to http://phonegap.com/
        <access origin="http://phonegap.com" subdomains="true" />  - same as above, but including subdomains, such as http://build.phonegap.com/
        <access origin="http://phonegap.com" browserOnly="true" /> - only allows http://phonegap.com to be opened by the child browser.
    -->

</widget>

当我在浏览器中打开index.html时,我可以看到地图。但是,当我制作.apk时,我看不到任何东西。我可以看到OL的控件,如缩放按钮和缩放。

这是我的map.js文件:

//Globals
var map;
var gpswatch;
var gpsmarker;
var startview = setnewView(739207,6404074,4);
var zoomres = 4.777314267823516;
var maxZoomlevel = 19;
var rotateMap = false;
var compasswatchID = null;

var layers = [
        new ol.layer.TileLayer({
          source: new ol.source.MapQuestOSM(),
          visible:true
        }),
        new ol.layer.TileLayer({
          source: new ol.source.OSM(),
          visible:false
        }),
        new ol.layer.TileLayer({
          source: new ol.source.MapQuestOpenAerial(),
          visible:false
        })
      ];

// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);

 // Cordova is ready
 function onDeviceReady() {   
    navigator.splashscreen.show();  
 }

//Initialisieren
$(document).ready(function(){
    setmapsize();
    $('#compassneedle').hide(); 
    map = new ol.Map({
      controls: ol.control.defaults({}, [
        new ol.control.ScaleLine({
          units: ol.control.ScaleLineUnits.IMPERIAL
        })
      ]),
      layers: layers,
      renderers: ol.RendererHints.createFromQueryData(),
      target: 'map',
      view: startview 
    });

    //Resizen der Map
    $(window).resize(function() {
        setmapsize();
    });

    map.getView().setRotation(getRadians(0));
    //map.getView().setCenter(getTranspoint(8,51,4326,900913));

    //GPS Marker
    gpsmarker = new ol.Overlay({
      map: map,
      element: /** @type {Element} */ ($('<i/>').addClass('gpspoint').get(0))
    });

    //GPS Status ändern
    $("#gpsstatus").change(function(){
        var mystatus = this.value;
        if(mystatus === "on"){
            startgpsWatch();
        }
        else{
            stopgpsWatch();
        }
    });

    //Compass Status ändern
    $("#compassstatus").change(function(){
        var mystatus = this.value;
        if(mystatus === "on"){
            startCompassWatch();
            $('#compassmapstatusdiv').show();
        }
        else{
            stopCompassWatch();
            map.getView().setRotation(getRadians(0));
            $('#compassmapstatusdiv').hide();
        }
    });

    //Karte Rotieren
    $("#compassmapstatus").change(function(){
        var mystatus = this.value;
        if(mystatus === "on"){
            rotateMap = true;
        }
        else{
            rotateMap = false;
            map.getView().setRotation(getRadians(0));
        }
    });

    $('#compassmapstatusdiv').hide();

    //Change Layer quick and dirty
    $('input[name=bglayer]:radio').click(function(){
        jQuery.each(layers, function(index, value) {
               this.setVisible(false);
         });
        layers[$(this).val()].setVisible(true);
    });


});

//Aktuelle Mapparameter ausgeben (Hilfsfunktion)
function getMapinfo(){
    var msg = '<div id="infomessagebox">' +
    'Actual Resolution: ' + startview.getResolution() + "<br>" +
    //'Actual Zoom: ' + startview.zoom + "<br>" +
    '</div>';
    $('#infomessage').html(msg);
}

//Auf Punkt zoomen
function zoomPoint(point,zoomres){
//Ansicht wechseln mit Animation
 var duration = 1000;
  var start = +new Date();
  var pan = ol.animation.pan({
    duration: duration,
    source: startview.getCenter(),
    start: start
  });
  var bounce = ol.animation.bounce({
    duration: duration,
    resolution: 4 * startview.getResolution(),
    start: start
  });
  //Flightmodus
  //map.addPreRenderFunctions([pan, bounce]);
  //Panmodus
  //map.addPreRenderFunction(pan);
  //Falls aktuelle Zoomresolution kleiner als übergebene
  if(startview.getResolution() < zoomres){
      zoomres = startview.getResolution();
  }
  startview.setResolution(zoomres);
  startview.setCenter(point);  
}

//Radians ermitteln
function getRadians(d){
    var radians = d * (Math.PI / 180);
    return radians;
}

//Punkt ermitteln
function getTranspoint(x,y,i,o){
 var mypoint = ol.projection.transform(
    [x, y], 'EPSG:'+i, 'EPSG:'+o);
    return mypoint;
}

//neuen View erzeugen
function setnewView(x,y,z){
var myview = new ol.View2D({
      center: [x, y],
      zoom: z,
      maxZoom: maxZoomlevel
    })
    return myview;
}

//GPS Start Watch Funktion
var startgpsWatch = function(){
    if(navigator.geolocation){
        $('#gpsmessage').html('<div id="gpsmessagebox">start watching...</div>');
        gpswatch = navigator.geolocation.watchPosition(gpsokCallback, gpsfailCallback, gpsOptions);
    }
}

//GPS Stop Watch  Funktion
var stopgpsWatch = function(){
    navigator.geolocation.clearWatch(gpswatch);
    $('.gpspoint').hide();
    $('#gpsmessage').html("");
}

//GPS Erfolgs Callback
var gpsokCallback = function(position){
    var msg = '<div id="gpsmessagebox">' +
    'Lat: ' + position.coords.latitude + "<br>" +
    'Lon: ' + position.coords.longitude + "<br>" +
    'Accuracy: ' + Math.round(position.coords.accuracy) + " m<br>" +
    //'Höhe: ' + Math.round(position.coords.altitude) + " m NN<br>" +   
    //'Präzision Höhenmessung: ' + Math.round(position.coords.altitudeAccuracy) + "<br>" +
    //'Richtung: ' + Math.round(position.coords.heading) + "<br>" +
    //'Geschwindigkeit: ' + Math.round(position.coords.speed) + 
    '<a href="#" id="setGpspoint" data-role="button" data-icon="arrow-r" data-iconpos="right" data-inline="true"  data-mini="true" >Zoom to position</a></div>';
    $('#gpsmessage').html(msg);
    var gpscoord = getTranspoint(position.coords.longitude,position.coords.latitude,4326,900913);
    gpsmarker.setPosition(gpscoord);
    $('.gpspoint').show();
    $("#setGpspoint").bind( "click", function(event, ui) {
        zoomPoint(gpscoord,zoomres);
    });
    $("#setGpspoint").button();
};

//GPS Fehler Callback
var gpsfailCallback = function(e){
    var msg = 'Fehler ' + e.code + ': ' + e.message;
    //console.log(msg);
};

//GPS Optionen
var gpsOptions = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
};

//Mapsize auf vollen Contentbereich skalieren.
function setmapsize(){
    window.scrollTo(0,0);
    var winhigh = $.mobile.getScreenHeight(); //Get available screen height, not including any browser chrome
    var headhigh = $('[data-role="header"]').first().outerHeight(); //Get height of first page's header
    var foothigh = $('[data-role="footer"]').first().outerHeight(); //Get height of first page's header
    var $content=$('[data-role="content"]');
    var contentpaddingheight=parseInt($content.css("padding-top").replace("px", ""))+parseInt($('[data-role="content"]').css("padding-bottom").replace("px", ""));
    winhigh = winhigh - headhigh - foothigh - contentpaddingheight; 
    $("#map").css('height',winhigh + 'px'); //Change div to maximum visible area
}

任何人都可以在我的代码中提出错误的建议,因为它与github完全相同。但是当我尝试制作.apk文件时,它不会在我的设备中显示mapp。

感谢任何帮助。

此致 甲-J

1 个答案:

答案 0 :(得分:1)

@ A〜J,
您需要添加白名单,插件和CSP OR 将版本设置为编译器。

注意:如果您没有设置版本,则可能会出现一组级联错误。但是,也许你可以添加 white-list ,一切都会按预期工作。

选项:

  1. <preference name="phonegap-version" value="3.5.0" />
  2. White List Guide
  3. 为了更好地理解 阅读#6,#7,#10&amp; Top Mistakes by Developers new to Cordova/Phonegap

    的#11

    最好的运气