|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
   AutoIt (Programación) Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  Teleco - Emisora de A.M. Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


Nuevo concurso para España, Argentina, Brasil, Chile, Colombia, Ecuador, México, Perú y Portugal.

B4A en español - Juan Antonio Villalpando
(BASIC4Android)

-- Tutorial de B4A --

Volver al índice del tutorial

____________________________

53CB.- Mapa de Google y archivos. GPS. Marcas.

- Seguimos con los mapas, en esta ocasión obtendremos la localización mediante GPS.

- De los tres ejemplo que presento en este tutorial aconsejo que comiences por el tercero.

_______________
- Designer.

- Creamos un Layout con un Button1 y un WebView1.

- Activamos la Librería GPS.

_______________
- Código.

Código - 1
Sub Process_Globals
    Dim gpsdato As GPS
    Dim Location1 As Location
End Sub
 
Sub Globals
    Dim Button1 As Button
    Dim WebView1 As WebView
End Sub
 
Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        gpsdato.Initialize("gpsdato")
        Location1.Initialize
    End If
End Sub
 
Sub Activity_Resume
    Activity.LoadLayout("layout")
End Sub
 
Sub Activity_Pause (UserClosed As Boolean)
 
End Sub
 
Sub Button1_Click
    If gpsdato.GPSEnabled=False Then
        ToastMessageShow("Habilita el GPS.", True)
        StartActivity(gpsdato.LocationSettingsIntent)
    Else
        gpsdato.Start(0, 0)
        ProgressDialogShow("GPS buscando localización.")
    End If
End Sub

' Ver información más adelante en el tutorial para cambiar esta parte.
 
Sub gpsdato_LocationChanged (gpsLocation As Location)
    ProgressDialogHide
    Location1=gpsLocation
    gpsdato.Stop
 
    ProgressDialogShow("Espera.")
    WebView1.LoadUrl("file:///android_asset/mapa.htm?lat="&Location1.Latitude&"&lng="&Location1.Longitude&"&zoom=8")
End Sub
 
Sub WebView1_PageFinished (Url As String)
    ProgressDialogHide
End Sub

- Ahora copiamos la siguiente información en un archivo llamado mapa.htm, este archivo lo copiamos en la carpeta Files del proyecto.

mapa.htm copiarlo en la carpeta Files
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html{
    height:100%;
}
body{
    height:100%;
    margin:0px;
    padding:0px;
}
#locationMap{
    height:100%;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
function initialize(){
    function getQueryObject(){
        //    getQueryObject() returns an object literal of name/values from the map page's URL if any are present
        var query=location.search, args={};
        query=query.length>0?query.substring(1):'';
        var items=query.split('&'), item, name, value, i;
        for(i=0; i<items.length; i++){
            item=items[i].split('=');
            name=decodeURIComponent(item[0]);
            value=decodeURIComponent(item[1]);
            args[name]=value;
        }
        return args;
    }
    var map, mapOptions={}, query=getQueryObject(), marker, markerOptions={}, lat=0, lng=0, zoom=0, createMarker=false;
    if(query.lat && query.lng){
        lat=parseFloat(query.lat);
        lng=parseFloat(query.lng);
        createMarker=true;
    }
    if(query.zoom){
        zoom=parseInt(query.zoom);
    }
    mapOptions.zoom=zoom;
    mapOptions.center=new google.maps.LatLng(lat, lng);
    mapOptions.mapTypeId=google.maps.MapTypeId.ROADMAP;
    map=new google.maps.Map(document.getElementById('locationMap'), mapOptions);
    if(createMarker){
        markerOptions.map=map
        markerOptions.position=new google.maps.LatLng(lat, lng);
        marker=new google.maps.Marker(markerOptions)
    }
}
</script>
</head>
<body onLoad="initialize()">
    <div id="locationMap"></div>
</body>
</html>

________________
- Comentarios.

- El GPS nos dará nuestra posición y el WebView nos la mostrará mediante los mapas de Google.

NOTA: en algunos móviles no me ha funcionado el código anterior, así que he modificado la última parte de este.
Renombro y Copio el archivo "mapa.htm" desde el DirAssets al DirRootExternal, cambiándolo de nombre.
Luego le hago un WebView1 a ese archivo.

- Con este código hay que habilitar la librería phone.

Código - 2 (Corrección del código anterior)

(...........)

Sub gpsdato_LocationChanged (gpsLocation As Location)
    ProgressDialogHide
    Location1=gpsLocation
    gpsdato.Stop
 
    ProgressDialogShow("Espera.")
    ToastMessageShow("Lat= " & Location1.Latitude & "Long= " & Location1.Longitude, True)
 RenameFile(File.DirRootExternal & "mapa.htm", File.DirRootExternal & "mapa.htm?lat="&Location1.Latitude&"&lng="&Location1.Longitude&"&zoom=8")
' WebView1.LoadUrl("file:///android_asset/mapa.htm?lat="&Location1.Latitude&"&lng="&Location1.Longitude&"&zoom=8")
' File.Copy(File.DirAssets, "mapa.htm", File.DirRootExternal,"mapa.htm?lat="&Location1.Latitude&"&lng="&Location1.Longitude&"&zoom=8")
WebView1.LoadUrl("file://" & File.DirRootExternal & "/mapa.htm?lat="&Location1.Latitude&"&lng="&Location1.Longitude&"&zoom=8")
End Sub
 
Sub WebView1_PageFinished (Url As String)
    ProgressDialogHide
End Sub
 
Sub RenameFile(OriginalFileName As String, NewFileName As String) As Boolean
   Dim Result As Int
   Dim StdOut, StdErr As StringBuilder
   StdOut.Initialize
   StdErr.Initialize
   Dim Ph As Phone
   Result = Ph.Shell("mv " & OriginalFileName & " " & NewFileName, Null,  StdOut, StdErr)
   If Result = 0 Then
      Return True
   Else
      Return False
   End If
End Sub

__________________________________

2. Vamos con otro.

- En esta ocasión presentamos un mapa con varias marcas, indicadores o dibujos.

- La mayoría del código principal está en el archivo mapa.htm que se encuentra en la carpeta Files.

- En la carpeta Files también copiamos estos archivos de imágenes que serán los que se muestre:

            

- Creamos un layout y le ponemos un WebView1 a pantalla completa.

- Saldrá un mapa y en su localización correspondiente saldrán esas dos imágenes.

Código
Sub Process_Globals
 
      
End Sub
 
Sub Globals
    Dim WebView1 As WebView
End Sub
 
Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("layout") 
    WebView1.LoadUrl("file:///android_asset/mapa.htm")
End Sub
 
Sub Activity_Resume
 
End Sub
 
Sub Activity_Pause (UserClosed As Boolean)
 
End Sub

mapa.htm en la carpeta Files.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<!--    add some CSS styles to make the map fill the WebView    -->
<style type="text/css">
html{
    height:100%;
}
body, #map_canvas{
    height:100%;
    margin:0px;
    padding:0px;
}
</style>
<!-- Reference to the map control -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
 
function initialize() {
    var myLatlng = new google.maps.LatLng(36.7983331,-5.5708481);
    // Centro del mapa en "LatLng"
    var myOptions = {
        zoom: 10,
        // Nivel inicial de Zoom. Se puede utilizar desde  0 a 20
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.HYBRID
        // Tipo de mapa
        // HYBRID - displays a transparent layer of major streets on satellite images
        // ROADMAP - displays a normal street map 
        // SATELLITE - displays satellite images
        // TERRAIN - displays maps with physical features such as terrain
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var infowindow = new google.maps.InfoWindow();
    // set the variable infowindow 
    
    //    create a LatLngBounds object
    var bounds=new google.maps.LatLngBounds();
    
    //********************* Dibujo de PUERTO REAL ******************************
    var Puerto_Real_marker = new google.maps.Marker
    // set the variable marker
    ({
        position: new google.maps.LatLng(36.5287811,-6.1923722),
        // set the geographic position for the marker
        map: map,
        // puts the marker on the specified map 
        title: "Puerto Real",
        // text that will display when the mouse cursor hovers over the marker
        icon: 'puerto_real.gif'
        // location of image file that will be used as a marker
    });
    google.maps.event.addListener
    // Event addlistener for info window of marker
    (
    Puerto_Real_marker,
    // associates the action with the marker named marker
    'click',
    // declares which event will trigger the event
    // Valid values are as follows
    // click, dblclick, mousedown, mousemove, mouseout, mouseover,mouseup, rightclick 
 
    function () {
        infowindow.setContent('<font color=#FF00FF>Puerto Real, sol y pinos.</font>');
        // sets the content for the info window (any valid html will do here
        infowindow.open(map, Puerto_Real_marker);
        // sets the info window to open based on the event
    });
    
    //    extend the bounds object with the Puerto_Real_marker position
    bounds.extend(Puerto_Real_marker.getPosition());
    
    //****************************** Dibujo de Jerez de la Frontera  *****************************
    var Jerez_marker = new google.maps.Marker({
        position: new google.maps.LatLng(36.682452,-6.1407201),
        map: map,
        title: "Jerez de la Frontera",
        icon: 'jerez.gif'
    });
    google.maps.event.addListener(
    Jerez_marker, 'click', function () {
        infowindow.setContent('<font color=#FF00FF>Jerez, vinos y caballos.</font>');
        infowindow.open(map, Jerez_marker);
    });
    
    //    extend the bounds object with the Jerez_marker position
    bounds.extend(Jerez_marker.getPosition());
    
    //    fit the map to the markers
    map.fitBounds(bounds);
    
    //********************* Poner las marcas ******************************************
}
</script>
</head>
<title>Basic Google Map with an Image Marker v3</title>
<body bgcolor="#FFFFFF" onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>

__________________________________

3.- Tercer ejemplo.

- En este caso utilizamos un archivo XML para guardar las coordenadas.
- He seguido este tutorial: http://econym.org.uk/gmap/basic3.htm

Código
Sub Process_Globals
 
      
End Sub
 
Sub Globals
    Dim WebView1 As WebView
End Sub
 
Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("layout") 
    WebView1.LoadUrl("file:///android_asset/mapa5.htm")
End Sub
 
Sub Activity_Resume
 
End Sub
 
Sub Activity_Pause (UserClosed As Boolean)
 
End Sub

 

 

 

 

 

 

 

 

 

 

 

 

 

mapa5.htm en la carpeta Files.
http://econym.org.uk/gmap/basic3.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
  <head>
    <title>Google Maps</title>
    <script src="http://maps.google.com/maps?

file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAPDUET0Qt7p2VcSk6JNU1sBSM5jMcmVqUpI7aqV44cW1cEECiThQYkcZUPRJn9vy_TWxWvuLoOfSFBw" 

type="text/javascript"></script>
  </head>
  <body onunload="GUnload()">

    <!-- you can use tables or divs for the overall layout -->
    <table border=1>
      <tr>
        <td>
           <div id="map" style="width: 550px; height: 450px"></div>
        </td>
        <td width = 150 valign="top" style="text-decoration: underline; color: #4444ff;">
           <div id="side_bar"></div>
        </td>
      </tr>
    </table>
    <a href="basic3.htm">Back to the tutorial page</a>

    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
      However, it seems JavaScript is either disabled or not supported by your browser. 
      To view Google Maps, enable JavaScript by changing your browser options, and then 
      try again.
    </noscript>

    <script type="text/javascript">
    //<![CDATA[
    if (GBrowserIsCompatible()) {
      // this variable will collect the html which will eventualkly be placed in the side_bar
      var side_bar_html = "";
      // arrays to hold copies of the markers used by the side_bar
      // because the function closure trick doesnt work there
      var gmarkers = [];

      // A function to create the marker and set up the event window
      function createMarker(point,name,html) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });

        // save the info we need to use later for the side_bar
        gmarkers.push(marker);
        // add a line to the side_bar html
        side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
        return marker;
      }

      // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        GEvent.trigger(gmarkers[i], "click");
      }


      // create the map
      var map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng( 43.907787,-79.359741), 9);
      // Read the data from example.xml
      GDownloadUrl("example.xml", function(doc) {
        var xmlDoc = GXml.parse(doc);
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {
          // obtain the attribues of each marker
          var lat = parseFloat(markers[i].getAttribute("lat"));
          var lng = parseFloat(markers[i].getAttribute("lng"));
          var point = new GLatLng(lat,lng);
          var html = markers[i].getAttribute("html");
          var label = markers[i].getAttribute("label");
          // create the marker
          var marker = createMarker(point,label,html);
          map.addOverlay(marker);
        }

        // put the assembled side_bar_html contents into the side_bar div
        document.getElementById("side_bar").innerHTML = side_bar_html;
      });
    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

    // This Javascript is based on code provided by the
    // Community Church Javascript Team
    // http://www.bisphamchurch.org.uk/   
    // http://econym.org.uk/gmap/

    //]]>
    </script>
  </body>
</html>

En este archivo llamado example.xml, y cópiado en la carpeta Files están las coordenadas

Archivo example.xml
<markers>
<!-- Dont use copy and paste on this XML file, use "View Source" or "Save As"
What the browser displays is *interpreted* XML, not XML source. -->
<marker lat="43.65654" lng="-79.90138" html="Some stuff to display in the&lt;br&gt;First Info Window" label="Marker One" />
<marker lat="43.91892" lng="-78.89231" html="Some stuff to display in the&lt;br&gt;Second Info Window" label="Marker Two" />
<marker lat="43.82589" lng="-79.10040" html="Some stuff to display in the&lt;br&gt;Third Info Window" label="Marker Three" />
</markers>

 

 

 

 

 

 

__________________________
- Getting an API Key

- La clave KEY está limitada solo a un sitio y a un directorio de ese sitio que se ha de declarar cuando se solicita. Estas aplicaciones deben funcionar en un servidor web o en Android.

- Por ejemplo http://www.gmap.example/mysite, utiliza la misma clave que para http://www.gmap.example/mysite/, http://www.gmap.example/mysite/mypage.html, y http://www.gmap.example/mysite/page?arg=foo.

- Pero no es válida para http://gmap.example/mysite/mypage.html, http://differenthost.gmap.example/mysite, yhttp://www.gmap.example/mysite/mysubdir/page.html.

- Para obtener la clave entra en

https://code.google.com/apis/console/?noredirect#project:448182961486:access

- y según la quieras para una web o para un programa para Android, deberás pulsar un botón y escribir la información requerida.

________________________________________________

Algunos tutoriales:

' http://www.xml.com/pub/a/2005/08/10/google-maps.html?page=2
' https://developers.google.com/maps/tutorials/data/json_example
' http://econym.org.uk/gmap/

________________________________

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información