Google Maps API not working using Cordova

Asked

Viewed 919 times

0

I am developing an application for Android using Cordova, I am doing the geo localization working with the latitude and longitude of the user, taking this data, I create the map (the position of the user), and with this I create the markers (the markers on the map). On the desktop works perfectly, but when I emulate on mobile, nothing happens.

HTML code:

<!DOCTYPE>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <meta name="msapplication-tap-highlight" content="no" />
        <script type="text/javascript" src="js/jquery1-7.js"></script>
        <link rel="stylesheet" type="text/css" href="css/responsivo.css">
        <link rel="stylesheet" type="text/css" href="css/icons.css">
        <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
        <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
        <title>Hello World</title>
        <script>
        function _GET(name)
        {
          var url   = window.location.search.replace("?", "");
          var itens = url.split("&");

          for(n in itens)
          {
            if( itens[n].match(name) )
            {
              return decodeURIComponent(itens[n].replace(name+"=", ""));
            }
          }
          return null;
        }
        var log = _GET("log");
        </script>
        <link rel="stylesheet" type="text/css" href="css/maps.css">
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false" />
    </head>
    <body onload="initialize()" id="tela-login">

        <script>

            function initialize() {

                function _GET(name){

                    var url   = window.location.search.replace("?", "");
                    var itens = url.split("&");

                    for(n in itens){
                        if( itens[n].match(name) ){
                            return decodeURIComponent(itens[n].replace(name+"=", ""));
                        }
                    }
                    return null;

                }

                var latitude = _GET("lat");
                var longitude = _GET("lon");

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

                var settings = {
                    zoom: 14,
                    center: latlng,
                    mapTypeControl: true,
                    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
                    navigationControl: true,
                    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
                    mapTypeId: google.maps.MapTypeId.ROADMAP};

                var map = new google.maps.Map(document.getElementById("map_canvas"), settings);     

                    // AQUI É UM INDICADOR, E AQUI VAI O LOOP

                    var imagemPin = new google.maps.MarkerImage("images/google.png",
                        new google.maps.Size(50,50),
                        new google.maps.Point(0,0),
                        new google.maps.Point(25,50));

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

                    var Marcador = new google.maps.Marker({
                        position: Posicao,
                        map: map,
                        icon: imagemPin,
                        title:"LUGAR",
                        zIndex: 3});

                    google.maps.event.addListener(Marcador, "click", function() {
                        infoColinasWindow.open(map,Marcador);
                    });

                    var colinasString = "<div class='muralPin'><div class='imagemPin'><img src='felipe.jpg' style='width: 60%;'></div><div class='textoPin'><p>Olá eu sou o Felipe</p></div></div>";                

                    var infoColinasWindow = new google.maps.InfoWindow({
                        content: colinasString
                    });

                    //FIM DO INDICADOR

                    // AQUI É UM INDICADOR, E AQUI VAI O LOOP

                    var imagemPin = new google.maps.MarkerImage("images/google.png",
                        new google.maps.Size(50,50),
                        new google.maps.Point(0,0),
                        new google.maps.Point(25,50));

                    var Posicao = new google.maps.LatLng(-22.403954,-47.5717276);

                    var Marcador2 = new google.maps.Marker({
                        position: Posicao,
                        map: map,
                        icon: imagemPin,
                        title:"LUGAR",
                        zIndex: 3});

                    google.maps.event.addListener(Marcador2, "click", function() {
                        infoColinasWindow2.open(map,Marcador2);
                    });

                    var colinasString2 = "<div class='muralPin'><div class='imagemPin'><img src='mario.jpg' style='width: 60%;'></div><div class='textoPin'><p>Olá eu sou o Mario</p></div></div>";     

                    var infoColinasWindow2 = new google.maps.InfoWindow({
                        content: colinasString2
                    });

                    //FIM DO INDICADOR

            }

            </script>
        <div class="bartop-index-app">
            <div class="sair-index-app">

            </div>
            <div class="texto-bartop-index-app">
                <img src="img/logo.png">
            </div>
            <div class="login-v-index-app">
                <img src="https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-xpa1/t1.0-9/10440811_793958303957393_4162157372130782847_n.jpg">
            </div>
        </div>
        <div class="mapaMural">
            <div id="map_canvas" style=""></div>
        </div>
        <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>

JS Code:

<script>
    if (navigator.geolocation){
      navigator.geolocation.getCurrentPosition(getPosicao, displayError);
    }

    function getPosicao(position){
      var lat = position.coords.latitude;

      var lon = position.coords.longitude;

      window.location = 'mapaAll.html?lat='+lat+'&lon='+lon;
     }

     function displayError(error) {
      var errors = {
        0: "Erro Desconhecido",
        1: "Permissão negada",
        2: "Posição indisponível",
        3: "Timeout"
      };
      alert("Ocorreu um erro: " + errors[error.code]);
    }
    </script>

In JS code, I take the current location, and use window.location = 'mapaAll.html?lat='+lat+'&lon='+lon; passing latitude and longitude to HTML file.

Can someone help me?

1 answer

2

Your code presents some problems. The first thing to note is that when you are developing applications with Cordova or PhoneGAP you should always check by the event deviceready.

The way Cordova works is very simple, it creates a kind of browser that runs your HTML. It also records some functions in Javascript to make the integration native. This process takes a while, so Cordova adds this Listeners and then fires the event deviceready.

What may be happening is that you call Geo Location functions before Cordova has created the interface between Android.

Other problems that can be observed in your code is that in your function _GET you loop looking for parameters every time, make sure this is really necessary, this can make applications slow, especially on smartphones. One peculiarity is that Android may find that your application has crashed if at some point some loop does not end, this can leave your application completely stuck during the process. Search makes all processes geared to events.

In the part of your code you store the longitude and latitude data, you use the following code.

  var latitude = _GET("lat");
  var longitude = _GET("lon");
  var latlng = new google.maps.LatLng(latitude,longitude);

You are creating a map with the obtained function data _GET, that is, the longitude and latitude must be passed by the URL. That is, with the code presented you do not make any call to the Cordova API. Already in the part of your code that deals with Cordova, you can implement differently, you try to update the URL of the browser to create the map, but this can make the page reload, which is not something you can keep doing on Android. Also check if you added the plugin responsible for GeoLocation on Android.

One solution would be to adjust your code to wait for Cordova to fire the deviceready or do some kind of verification if your app is on a Smartphone or if it is running in the browser. Only then create the map based on location.

Another thing that can be improved is that currently you take location with data passed through the URL, you can change this and use the Geo Location HTML5.

If you find more problems you can check the errors found by Javascript inside the Android by opening the terminal and typing the command adb logcat "Cordovalog:D *:S", all Javascript errors and all output of console.log must be presented.

Browser other questions tagged

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