Mobile Cordova Geolocation

Asked

Viewed 1,767 times

0

I am developing an application that contains a register of the address that the person is, and I would like to get this data directly from the location service, but I would like to know if you could get the name and street number. I’ve seen some examples on the web that return latitude and longitude but there’s a way to get the address?

2 answers

1

Well, first it is necessary to add to your project the geolocation plugin, after this step, you should create a file of type HTML inside the briefcase WWW this file can be filled with the following code:

HTML:

<html>    
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Cadastro de notificação</title>

    <!--ARQUIVO DE ESTILO, NECESSÁRIO PARA RENDERIZAR O MAPA-->
    <link rel="stylesheet" href="css/estilo.css" />

    <!--SCRIPTS NECESSÁRIOS PARA A CRIAÇÃO DO MAPA-->
    <script src="https://maps.googleapis.com/maps/api/js?key=SUA_CHAVE_DA_API_GOOGLE_MAPS&callback=initMap" async defer></script>
    <script type="text/javascript" src="js/maps.js"></script>
</head>

<!-- AO INICIAR O BODY, A FUNÇÃO INITMAP SERÁ EXECUTADA-->
<body onload="initMap()">
    <div id="map"></div>

</body>
</html>

Remember that to use the Google Maps API, you need to get a key for use through the site of your documentation.

JAVASCRIPT:

function initMap() {
var sucesso = function(position) { 
// váriavel que receberá as coordenadas obtidas através do seu dispositivo
    var coords = position.coords; 

// váriavel que recebe as funções do google maps
    var map = new google.maps.Map(

//busca no HTML o id da div
        document.getElementById("map"), {

// ao iniciar, o mapa será centralizado nas coordenadas obtidas
            center: new google.maps.LatLng(coords.latitude, coords.longitude),
// definido o zoom do mapa
            zoom : 17, 
//não permite ao usuário mover o mapa
            draggable: false,
//desabilita o zoom quando ouver clique duplo 
            disableDoubleClickZoom: true,
//desabilita as interfaces de ferramentas padrão do google maps
            disableDefaultUI: true
        }
    );

//variável que receberá o marcador do google maps
    var marker = new google.maps.Marker({

//atribuição da posição do google maps através das coordenadas
        position: new google.maps.LatLng(coords.latitude, coords.longitude)
    });
// define o marcador na div map
    marker.setMap(map);        
}


var erro = function(error) {
    navigator.notification.alert("Erro ao capturar posição: " + error.message, "INFORMAÇÃO");
}

// Opções para acessar o GPS...
var opcoes = {
    maximumAge: 3000,
    timeout: 5000,
    enableHighAccuracy: true
};

// CAPTURAR POSIÇÃO: Chamada a API de Geolocalização (GPS) via Apache Cordova
navigator.geolocation.getCurrentPosition(sucesso, erro, opcoes);
}

CSS:

body {
  margin: 0;
}

#map {
 height: 250px;
 width: 100%;
}

0

GPS geolocation of the device using Phonegap, Google Maps API and jQuery Mobile

Phonegap’s Geolocation API provides information on device location, such as latitude and longitude, altitude, speed, and more.

Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, Wi-Fi and Bluetooth MAC addresses, and GSM / CDMA cell Ids. The jQuery Mobile framework was also used to display the contents of the app such as header, footer and map content.

geomap.js:

/**
 * AppGeolocationMap
 */
var map;
var marker;
var infowindow;
var watchID;
var msg;
 
$(document).ready(function() {
 document.addEventListener("deviceready", onDeviceReady, false);
 // for testing in Chrome browser uncomment
 // onDeviceReady();
});
 
// PhoneGap is ready function
function onDeviceReady() {
 $(window).unbind();
 $(window).bind('pageshow resize orientationchange', function(e) {
  max_height();
 });
 max_height();
 google.load("maps", "3.8", {
  "callback" : map,
  other_params : "sensor=true&language=en"
 });
}
 
function max_height() {
 var h = $('div[data-role="header"]').outerHeight(true);
 var f = $('div[data-role="footer"]').outerHeight(true);
 var w = $(window).height();
 var c = $('div[data-role="content"]');
 var c_h = c.height();
 var c_oh = c.outerHeight(true);
 var c_new = w - h - f - c_oh + c_h;
 var total = h + f + c_oh;
 if (c_h < c.get(0).scrollHeight) {
  c.height(c.get(0).scrollHeight);
 } else {
  c.height(c_new);
 }
}
 
function map() {
 var latlng = new google.maps.LatLng(-24.9555, -53.4552);
 var myOptions = {
  zoom : 6,
  center : latlng,
  streetViewControl : true,
  mapTypeId : google.maps.MapTypeId.ROADMAP,
  zoomControl : true
 };
 map = new google.maps.Map(document.getElementById("map"), myOptions);
 
 google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
  // get geoposition once
  // navigator.geolocation.getCurrentPosition(geo_success, geo_error, {
  // maximumAge: 5000, timeout: 5000, enableHighAccuracy: true });
  // watch for geoposition change
  watchID = navigator.geolocation.watchPosition(geo_success, geo_error, {
   maximumAge : 5000,
   timeout : 5000,
   enableHighAccuracy : true
  });
 });
}
 
function geo_error(error) {
 // comment
 alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
 
function geo_success(position) {
 map.setCenter(new google.maps.LatLng(position.coords.latitude,
   position.coords.longitude));
 map.setZoom(15);
 
 var info = ('Latitude: ' + position.coords.latitude + '
'
   + 'Longitude: ' + position.coords.longitude + '
' + 'Altitude: '
   + position.coords.altitude + '
' + 'Accuracy: '
   + position.coords.accuracy + '
' + 'Altitude Accuracy: '
   + position.coords.altitudeAccuracy + '
' + 'Heading: '
   + position.coords.heading + '
' + 'Speed: '
   + position.coords.speed + '
' + 'Timestamp: ' + new Date(
   position.timestamp));
 
 var point = new google.maps.LatLng(position.coords.latitude,
   position.coords.longitude);
 if (!marker) {
  // create marker
  marker = new google.maps.Marker({
   position : point,
   map : map
  });
 } else {
  // move marker to new position
  marker.setPosition(point);
 }
 if (!infowindow) {
  infowindow = new google.maps.InfoWindow({
   content : info
  });
 } else {
  infowindow.setContent(info);
 }
 google.maps.event.addListener(marker, 'click', function() {
  infowindow.open(map, marker);
 });
}
 
// exit app
function exitFromApp(buttonIndex) {
 if (buttonIndex === 2) {
  navigator.app.exitApp();
 }
}
// showConfirm exit app
function showConfirm() {
 navigator.notification.confirm('Deseja Realmente Sair?', exitFromApp,
   'Geolocation Map', 'Cancelar,OK' // buttonLabels
 );
}

index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
 content="width=device-width, minimum-scale=1, maximum-scale=1">
<title>Geolocation Maps</title>
 
<link rel="stylesheet" href="css/jquery.mobile-1.0.1.css" />
 
<script type="text/javascript" src="js/jquery-1.6.4.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.0.1.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="js/cordova-1.5.0.js"></script>
<script type="text/javascript" src="js/geomap.js"></script>
</head>
 
<body>
 <div data-role="page" id="index" onload="">
 
  <!-- header -->
  <div data-role="header" data-theme="a">
   <a data-role="button" data-icon="back" onclick="showConfirm()"
    data-iconpos="right" class="ui-btn-right">Sair</a>
   <h3>Geolocation Map</h3>
  </div>
 
  <!-- content #Map -->
  <div data-role="content" style="padding: 0;">
   <div id="map" style="width: 100%; height: 100%;"></div>
  </div>
 
  <!-- footer -->
  <div data-role="footer" data-theme="a" data-position="fixed">
   <div align="center" style="font-size: 12px; color: silver;">
    <div id="infoUser"></div>
   </div>
  </div>
 </div>
</html>

Source: http://robsonfagundes.blogspot.com.br/

  • Of course this example is basic but it is already a great starting point for you to arrive at your need

Browser other questions tagged

You are not signed in. Login or sign up in order to post.