0

Solamente deseo actualizar automáticamente mis marcadores y que cuando recoge una nueva ubicación de la base de datos, esta se actualice solo en el mapa.. pero no tengo idea de como hacer. Según leí se puede hacer con ajax

function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(-25.415896, -54.616280),
            zoom: 12
        });
        var infoWindow = new google.maps.InfoWindow;


        downloadUrl('complemento_audio.php', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('marker');
            Array.prototype.forEach.call(markers, function(markerElem) {
                var nombre = markerElem.getAttribute('nombre');
                var apellido = markerElem.getAttribute('apellido');
                var cedula = markerElem.getAttribute('cedula');
                var numero = markerElem.getAttribute('numero');
                var nacimiento = markerElem.getAttribute('nacimiento');
               // var direccion = markerElem.getAttribute('direccion');
                var fecha = markerElem.getAttribute('hor');
                var foto = markerElem.getAttribute('foto');
                var tipo = markerElem.getAttribute('tipo');

                var point = new google.maps.LatLng(
                    parseFloat(markerElem.getAttribute('lat')),
                    parseFloat(markerElem.getAttribute('lng')));

                var infowincontent = document.createElement('div');
                var strong = document.createElement('strong');
                strong.textContent = tipo + " en: "
                infowincontent.appendChild(strong);
               // infowincontent.appendChild(document.createElement('br'));

               /* var text21 = document.createElement('text21');
                text21.textContent = direccion
                infowincontent.appendChild(text21);
                infowincontent.appendChild(document.createElement('br'));*/

                var text2 = document.createElement('strong');
                text2.textContent = "Fecha y Hora:     "
                infowincontent.appendChild(text2);

                var text = document.createElement('text');
                text.textContent = fecha
                infowincontent.appendChild(text);
                infowincontent.appendChild(document.createElement('br'));

                var text3 = document.createElement('strong');
                text3.textContent = "Denunciado por:    "
                infowincontent.appendChild(text3);
                //infowincontent.appendChild(document.createElement('br'));

                var text22 = document.createElement('text22');
                text22.textContent = nombre + " " + apellido
                infowincontent.appendChild(text22);
                infowincontent.appendChild(document.createElement('br'));

                var text1 = document.createElement('strong');
                text1.textContent = "C.I.:      "
                infowincontent.appendChild(text1);

                var text11 = document.createElement('text11');
                text11.textContent = cedula
                infowincontent.appendChild(text11);
                infowincontent.appendChild(document.createElement('br'));

                var celular = document.createElement('strong');
                celular.textContent = "Celular:      "
                infowincontent.appendChild(celular);

                var cel_num = document.createElement('cel_num');
                cel_num.textContent = numero
                infowincontent.appendChild(cel_num);
                infowincontent.appendChild(document.createElement('br'));
                infowincontent.appendChild(document.createElement('br'));

                var elem = document.createElement('audio');
                elem.src = foto
                elem.controls = "true";
              //  elem.type = ("video/mp4");
               // elem.setAttribute("align", "center");
               // elem.setAttribute("width", "1024");
                infowincontent.appendChild(elem);

               /* var enlace = document.createElement('a');
               // enlace.textContent = "      Mas info ...";
               // enlace.setAttribute("background", "red");
                enlace.href = "jasdhasjk.com";
                enlace.target = "_blank"; // para que se abra en una nueva pestaña
                infowincontent.appendChild(enlace);
                infowincontent.appendChild(document.createElement('br'));*/

                var icon1 = 'img_web/icono_asdasdasdasdasdasd.gif';
                var marker = new google.maps.Marker({
                    map: map,
                    position: point,
                    icon: icon1,
                    draggable: true,
                   // animation: google.maps.Animation.DROP
                });
               // marker.setAnimation(google.maps.Animation.BOUNCE);
                marker.addListener('click', function() {
                    infoWindow.setContent(infowincontent);
                    infoWindow.open(map, marker);
                });
            });


        });
    }



    function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
            }
        };

        request.open('GET', url, true);
        request.send(null);
    }

    function doNothing() {}

mi codigo php

<?php
require("module/dbase.php");

function parseToXML($htmlStr){
    $xmlStr=str_replace('<','&lt;',$htmlStr);
    $xmlStr=str_replace('>','&gt;',$xmlStr);
    $xmlStr=str_replace('"','&quot;',$xmlStr);
    $xmlStr=str_replace("'",'&#39;',$xmlStr);
    $xmlStr=str_replace("&",'&amp;',$xmlStr);
    return $xmlStr;
}

// Select all the rows in the markers table
$result_markers = "SELECT u.nombre, u.apellido, u.cedula, u.numero, u.nacimiento, a.direccion, a.latitud, a.longitud, a.horario FROM usu_panico u, audio_panico a WHERE u.cedula = a.identificador";
$resultado_markers = mysqli_query($mysqli, $result_markers);

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row_markers = mysqli_fetch_assoc($resultado_markers)){
  // Add to XML document node
  echo '<marker ';
  echo 'nombre="' . parseToXML($row_markers['nombre']) . '" ';
  echo 'apellido="' . parseToXML($row_markers['apellido']) . '" ';
  echo 'cedula="' . parseToXML($row_markers['cedula']) . '" ';
  echo 'numero="' . parseToXML($row_markers['numero']) . '" ';
  echo 'nacimiento="' . parseToXML($row_markers['nacimiento']) . '" ';
 // echo 'direccion="' . parseToXML($row_markers['avenida']) . '" ';
  echo 'foto="' . parseToXML($row_markers['direccion']) . '" ';
  echo 'hor="' . parseToXML($row_markers['horario']) . '" ';
  echo 'lat="' . $row_markers['latitud'] . '" ';
  echo 'lng="' . $row_markers['longitud'] . '" ';
  echo 'tipo="' . $row_markers['denuncia'] . '" ';
  echo '/>';
}

// End XML file
echo '</markers>';

1 respuesta 1

1

No veo en qué caso podría cambiar tu array de markers, si en el backend siempre haces la misma consulta. Pero supongamos que llamas a tu función downloadUrl en varias ocasiones y obtienes resultados distintos.

Primero, debieras tener una variable marker_array accesible desde afuera de las funciones.

Segundo, después de recorrer el XML y crear cada marker, añadirlo a marker_array

Tercero, antes de llamar a downloadUrl varias los markers existentes

var marker_array=[];

function initMap() {
    ... codigo ...
    downloadUrl('complemento_audio.php', function(data) {
       var markers = xml.documentElement.getElementsByTagName('marker');
       Array.prototype.forEach.call(markers, function(markerElem) {
           ... más código ...
           var marker = new google.maps.Marker({
                    map: map,
                    position: point,
                    icon: icon1,
                    draggable: true,
           });

           marker_array.push(marker) // AQUI LO METES EN EL ARRAY

       });

}

function downloadUrl(url, callback) {
    // Antes de pedir un nuevo XML, 
    // procedo a vaciar mis markers existentes
    while(marker_array.length) {
        var marker = marker_array.pop();
        marker.setMap(null);
    }
    ... código ...
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.