地图未显示在Cordova Android中

时间:2018-05-16 15:08:37

标签: google-maps cordova geolocation

我已根据这些说明使用Cordova构建了一个Android应用 https://cordova.apache.org/docs/en/latest/guide/cli/index.html

一切正常,除了地图显示我运行模拟浏览器模拟android ,但不是当我将apk安装到我的J5三星手机时。

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *; img-src * data: 'unsafe-inline'">
    <!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' gap:; style-src 'self' 'unsafe-inline'; media-src *" />
    <!-- Good default declaration:
    * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
    * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
    * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
        * Enable inline JS: add 'unsafe-inline' to default-src
        * Enable eval(): add 'unsafe-eval' to default-src
    * Create your own at http://cspisawesome.com
    -->
    <!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-inline' https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *" /> -->

    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <title>Hello World</title>
</head>

<style type="text/css">
    html { height: 100% }
    body { height: 100%; margin: 0; padding: 0 }
    #map { height: 100% }
</style>

<body>
    <div class="app">
        <h1>PhoneGap</h1>
        <div id="deviceready" class="blink">
            <p class="event listening">Connecting to Device</p>
            <p class="event received">Device is Ready</p>

        </div>

    </div>
    <div id="geolocation"></div>

    <button type="button" onclick="addMarker()">Add Marker</button>

    <div id="map">MAP HERE</div>
    <script src="/__/firebase/4.13.0/firebase-app.js"></script>
    <script src="/__/firebase/4.13.0/firebase-auth.js"></script>
    <script src="/__/firebase/4.13.0/firebase-database.js"></script>
    <script src="/__/firebase/4.13.0/firebase-messaging.js"></script>
    <script src="/__/firebase/4.13.0/firebase-functions.js"></script>

    <!-- Leave out Storage -->
    <!-- <script src="/__/firebase/4.13.0/firebase-storage.js"></script> -->

    <script src="/__/firebase/init.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA8RwcNCgxRCRpiSgiRpr_InT2Vt-aDwPQ" type="text/javascript"></script>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
        app.initialize();
    </script>
</body>

</html>

<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script>
<script>
    // Initialize Firebase
    var config = {
        .............
    };
    firebase.initializeApp(config);
</script>

和js文件

var test=5;
var json = [
    {
        lat: 55.5,
        lng: -4
    },
    {
        lat:56,
        lng: -4.5
    }
];

var Latitude = undefined;
var Longitude = undefined;

// Get geo coordinates

function getMapLocation() {

    navigator.geolocation.getCurrentPosition
    (onMapSuccess, onMapError, { enableHighAccuracy: true });
}

// Success callback for get geo coordinates

var onMapSuccess = function (position) {

    Latitude = position.coords.latitude;
    Longitude = position.coords.longitude;

    getMap(Latitude, Longitude);
};

// Get map by using coordinates

function getMap(latitude, longitude) {

    var mapOptions = {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map
    (document.getElementById("map"), mapOptions);


    var latLong = new google.maps.LatLng(latitude, longitude);

    var marker = new google.maps.Marker({
        position: latLong
    });

    //marker.setMap(map);
    map.setZoom(9);
    map.setCenter(marker.getPosition());


    showMarkers();
}

// Success callback for watching your changing position

var onMapWatchSuccess = function (position) {
    var updatedLatitude = position.coords.latitude;
    var updatedLongitude = position.coords.longitude;

    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {

        Latitude = updatedLatitude;
        Longitude = updatedLongitude;

        getMap(updatedLatitude, updatedLongitude);
    }
};

// Error callback

function onMapError(error) {
    console.log('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

// Watch your changing position

function watchMapPosition() {
    return navigator.geolocation.watchPosition
    (onMapWatchSuccess, onMapError, { timeout: 30000 });
}

function showMarkers(){
    for(var i=0;i<json.length;i++) {
        data = json[i];
        var latLong = new google.maps.LatLng(data.lat, data.lng);
        var marker = new google.maps.Marker({
            position: latLong
        });
        marker.setMap(map);
    }
}

function addMarker(){
    var newMarker = new Object();
    newMarker["lat"] = Latitude;
    newMarker["lng"] = Longitude;
    writeCoords("abc",Latitude, Longitude);
    json.push(newMarker);
    showMarkers();
}

function readMarkers(){
    var activeRef = firebase.database().ref('location/');

    activeRef.on('value', function(snapshot){
        snapshot.forEach(function(childSnapshot) {
            alert(childSnapshot.val().latitude);
        });
    });
}
watchMapPosition();


function writeCoords(userId, lat, lng){
    firebase.database().ref('location/' + firebase.database().ref().child('location').push().key).set({
        latitude: lat,
        longitude: lng
    });
}

var app = {
    // Application Constructor
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function() {
        this.receivedEvent('deviceready');
    },

    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

app.initialize();

这样的config.xml可能就是问题所在

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.hello" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>HelloWorld</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
    <engine name="android" spec="~6.1.2" />
</widget>

所有在模拟器上工作正常,我可以使用标记按钮上传到Firebase。当它移动到手机本身时,我会看到除地图之外的所有内容。

1 个答案:

答案 0 :(得分:0)

我做了两件事。已安装 cordova插件添加cordova-plugin-geolocation 并在安装后从手机上拔下usb。不确定两者是否都是必需的,但它现在有效。