Как управлять широтой и долготой моего андроид телефона в кордове? - PullRequest
0 голосов
/ 22 сентября 2018

Пожалуйста, помогите!Как узнать широту и долготу моего телефона по нажатию кнопки "# btn_2"?для index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/bootstrap.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
</head>
<body onload="Ready()">
    <div class=".app">
        <form style="padding: 15px" id="form_1" name="form_1">
            <br>
            <button type="Submit" id="btn_2">geo location</button>
        </form>
        <span id="result"></span>
    </div>
</body>
</html>

для index.js:

function Ready(){
document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady(){
$(document).ready(function(){
    $('#btn_2').click(function(){
        navigator.geolocation.getCurrentPosition(onSuccess, onError, { 
timeout: 5000, enableHighAccuracy: true });
    });
});
}
var onSuccess = function(position) {
    alert('Latitude: '          + position.coords.latitude          + '\n' +
          'Longitude: '         + position.coords.longitude         + '\n' +
          'Altitude: '          + position.coords.altitude          + '\n' +
          'Accuracy: '          + position.coords.accuracy          + '\n' +
          'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
          'Heading: '           + position.coords.heading           + '\n' +
          'Speed: '             + position.coords.speed             + '\n' +
          'Timestamp: '         + position.timestamp                + '\n');
};

function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}

при попытке нажать кнопку в моем телефоне не отображается ни предупреждение, ни предупреждение об успехе, ни ошибка,пожалуйста, помогите!

1 Ответ

0 голосов
/ 22 сентября 2018

Когда вы нажимаете кнопку, она отправляет вашу форму "form_1" и, возможно, страница перезагружается.Это может быть причиной.Попробуйте переместить кнопку из формы или добавить другую без type = "submit".

В первый раз, когда вы пытаетесь проверить геолокацию, вас могут спросить о разрешениях.Убедитесь, что вы не отрицали это, моя ошибка.

Также вы можете попробовать переустановить плагин геолокации

cordova plugin add cordova-plugin-geolocation

Вот мой рабочий код

<div class="app">
        <h1>Apache Cordova</h1>
        <div id="deviceready" class="blink">
            <p class="event listening">Connecting to Device</p>
            <p class="event received">Device is Ready</p>
            <button id="geo-button" class="button">Geo</div>
        </div>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>

index.js

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);

    const geoButton = document.getElementById('geo-button');

    geoButton.addEventListener('click', function(e) {
        navigator.geolocation.getCurrentPosition(function(position) {
            alert('Latitude: '          + position.coords.latitude          + '\n' +
              'Longitude: '         + position.coords.longitude         + '\n' +
              'Altitude: '          + position.coords.altitude          + '\n' +
              'Accuracy: '          + position.coords.accuracy          + '\n' +
              'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
              'Heading: '           + position.coords.heading           + '\n' +
              'Speed: '             + position.coords.speed             + '\n' +
              'Timestamp: '         + position.timestamp                + '\n');
        }, function onError(error) {
            alert('code: '    + error.code    + '\n' +
                'message: ' + error.message + '\n');
        });
    });
}}

Также не забудьте добавить его для iOS

<edit-config file="*-Info.plist" mode="merge" target="NSLocationWhenInUseUsageDescription">
    <string>need location access to find things nearby</string>
</edit-config>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...