Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Oct 2011
    Posts
    66
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Add and update markers in google map with Ajax

    Hello,
    I am desperate, just finished a very big project, and they just changed the way the markers on the google map has to be displayed.

    At this moment I do an xml call and get available dates and coordinates for the markers. Is working perfect.
    However they just changed and want the markers displayed as per each date,...that means I have to do another xml call to get the coordinates for the date choosen in a calendar.
    So I have to be able to add markers but also delete and put new ones.

    I Suppose the best for this is to use Ajax, however I have only done simple things with ajax (pure javascript only).

    So I get the coordinates in the php file
    This would be the part that I would have to pass to ajax from phpfile called by ajax:
    PHP Code:
    <?php

    $paradasarray 
    json_encode($paradasarray);
    $paradax '';
     
    $paradasarray json_decode($paradasarray);
    $paradax2 = array();
      foreach (
    $paradasarray as $parada) {
         [
    B]    $hora $parada->horarecogida->{'0'};
             
    $paradax $parada->nombreparada;
             
    $idparada $parada->idparada->{'0'};
                
    $lat $parada->lat->{'0'};
                
    $lng $parada->lng->{'0'};[/B]
            }
            
    ?>
    This is the map in question, I need to update the markers and html in the infowinfows:
    PHP Code:
    <div id="map" style="width: 100%; height:300px"></div>
    <script>

    var infowindow = null;
    var markers = [];
    function initMap(){
       var myLatlng = new google.maps.LatLng(36.5505197,-4.8349095);
       var myOptions = {
          zoom: 10,
          center: myLatlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
       };

       var citiesObject = [
          {
             name: 'Benalmádena Costa',
             lat: 36.5985811,
             lon: -4.5184101,
             zoom: 14
          },
          {
             name: 'Torrequebrada',
             lat: 36.5843169,
             lon: -4.5353021,
             zoom: 14
          },
          {
             name: 'Almuñecar',
             lat: 36.7363573,
             lon: -3.6936177,
             zoom: 14
          },
          {
             name: 'Estepona',
             lat: 36.4078757,
             lon: -5.1877823,
             zoom: 11
          },
          {
             name: 'Atalaya-Benavista',
             lat: 36.4660413,
             lon: -5.0289864,
             zoom: 13
          },
          {
             name: 'Fuengirola',
             lat: 36.5457253,
             lon: -4.6281043,
             zoom: 13
          },
          {
             name: 'Carvajal',
             lat: 36.5712203,
             lon: -4.6022271,
             zoom: 13
          },
          {
             name: 'Málaga Capital',
             lat: 36.7139351,
             lon: -4.424794,
             zoom: 14
          },
          {
             name: 'Marbella Town',
             lat: 36.5112345,
             lon: -4.8869307,
             zoom: 14
          },
          {
             name: 'Marbella East',
             lat: 36.5053049,
             lon: -4.7980592,
             zoom: 13
          },
          {
             name: 'Marbella West',
             lat: 36.4963191,
             lon: -4.9380258,
             zoom: 13
          },
          {
             name: 'Marbella San Pedro',
             lat: 36.4772001,
             lon: -4.9984498,
             zoom: 13
          },

          {
             name: 'La Cala',
             lat: 36.5022141,
             lon: -4.6806549,
             zoom: 14
          },
          {
             name: 'Calahonda',
             lat: 36.4923402,
             lon: -4.7129583,
             zoom: 14
          },
          {
             name: 'Nerja',
             lat: 36.7593257,
             lon: -3.871842,
             zoom: 13
          },
          {
             name: 'Torre del Mar',
             lat: 36.7389255,
             lon: -4.095758,
             zoom: 13
          },
          {
             name: 'Torremolinos',
             lat: 36.6265478,
             lon: -4.4949926,
             zoom: 14
          },
          {
             name: 'La Carihuela',
             lat: 36.6138008,
             lon: -4.5055638,
             zoom: 14
          },
          {
             name: 'Torrox',
             lat: 36.7350957,
             lon: -3.9585594,
             zoom: 13
          },
       ];

       citiesObject.forEach((city) => {
          if (document.getElementById("city").value === city.name) {
             myLatlng = new google.maps.LatLng(city.lat,city.lon,);
             myOptions = {
                zoom: city.zoom,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
             };
          }
       });

       var map = new google.maps.Map(document.getElementById('map'), myOptions);

       infowindow = new google.maps.InfoWindow({
          content: "holding..."
       });

       <?php
       $paradax 
    '';
       
    $paradasarray json_decode($paradasarray);
       foreach (
    $paradasarray as $parada) {
          
    $hora $parada->horarecogida->{'0'};
          
    $paradax $parada->nombreparada;
          
    $idparada $parada->idparada->{'0'};
     
          
    ?>

          var marker = new google.maps.Marker({
            position: new google.maps.LatLng(<?php echo $parada->lat->{'0'} . ", " $parada->lng->{'0'}  ?>),
            map: map,
          html: "<?php echo $paradax?><br><?php echo $lang_pickuptime." ".$hora?><br><br><?php echo $lang_eligaeste?> <input name='elegirparada' type='checkbox' id='elegirparada' value='1'><br><input type='hidden'  id='paradax' value='<?php echo $paradax?>'><input type='hidden' value='<?php echo $idparada?>' id='idparada'><div id='errortext'></div>"
          });

          markers.push(marker);

          google.maps.event.addListener(marker, 'click', function () {
             infowindow.setContent(this.html);
             infowindow.open(map, this);
           });
          <?php
       
    }
       
    ?>

       google.maps.event.addListener(infowindow, 'domready', function() {
          defineListener();
       });
    }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=rrrr&callback=initMap&language=en"
    async defer></script>
    <p style="display: none;" id="elegidotexto"><?php echo $lang_elegido?>
       <span id="elegidotexto2"> </span></p>
       <input type="hidden" id="pickupoint" name="pickupoint" value="">
       <input type="hidden" id="puntorecoger" name="puntorecoger" value="">
       <script>
       function defineListener() {
          var elegirParadaEl = document.getElementById("elegirparada");

          elegirParadaEl.addEventListener("change", function(){
             // Get the checkbox
             var checkBox = document.getElementById("elegirparada");
             // Get the output text
             var text = document.getElementById("elegidotexto");

             // If the checkbox is checked, display the output text
             if (checkBox.checked == true){
                text.style.display = "block";
             } else {
                text.style.display = "none";
             }
             document.getElementById("elegidotexto2").innerHTML = document.getElementById("paradax").value;
             document.getElementById("puntorecoger").value= document.getElementById("paradax").value;
             document.getElementById("pickupoint").value = document.getElementById("idparada").value;                                 // window.sessionStorage.setItem('pickupointguardar', document.getElementById("idparada").value);
          });
          var divErrortext = document.getElementById('errortext'),
          valid = true;
          var element2 = document.querySelector('#elegirparada');
          if (element2 !== null) {
             element2.addEventListener('click', () => {
                  if (document.solicitud.plazasDisponibles.value == ''){
                    console.log(element2)
                      divErrortext.innerHTML="<span style='color:red'><?php echo $lang_val_choosedate ?></span>";
                      return false;
                  }
             })
          }
       }
       var element = document.querySelector('#city');
       element.addEventListener('change', () => {
          initMap()
       })

       </script>
    Any help is apple¡coated

  2. #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Location
    Here
    Posts
    3,928
    Thanks
    58
    Thanked 699 Times in 694 Posts
    Hola Helenp,

    I'm not sure that I understand your question 100%.

    Are you saying that you need to put the date in the infowindows and also to be able to show or hide the markers based on their date?

  3. #3
    New Coder
    Join Date
    Jan 2019
    Location
    USA
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    So I finally did it . With help form various different sources and all! here us the complete code :

    <?php
    error_reporting(E_ALL ^ E_DEPRECATED);

    $conn = mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("vsms3") or die(mysql_error());
    ?>

    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps</title>

    <!-------- Customizable Css for Map ----------------------------->
    <style type="text/css">
    body { font: normal 10pt Helvetica, Arial; }
    #map { width: 500px; height: 300px; border: 0px; padding: 0px; }
    </style>

    <!---------------- Java Scripts for Map ----------------->
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyDzaa4MZ7r4s26i54PwErpKTynKAaWVxTc&v=3&language=en"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
    <!------------- Java Scripts for Map ------------------->
    <script type="text/javascript">
    var marker;
    var map = null;
    var markersArray = [];

    //--------------------- Sample code written by vIr ------------
    var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
    new google.maps.Size(32, 32), new google.maps.Point(0, 0),
    new google.maps.Point(16, 32));
    var center = null;

    var currentPopup;
    var bounds = new google.maps.LatLngBounds();
    function addMarker(lat, lng, info) {
    var pt = new google.maps.LatLng(lat, lng);
    bounds.extend(pt);
    marker = new google.maps.Marker({
    position: pt,
    draggable: true,
    raiseOnDrag: true,
    icon: icon,
    map: map
    });
    markersArray.push(marker);
    var popup = new google.maps.InfoWindow({
    content: info,
    maxWidth: 300
    });
    google.maps.event.addListener(marker, "click", function() {
    if (currentPopup != null) {
    currentPopup.close();
    currentPopup = null;
    }
    popup.open(map, marker);
    currentPopup = popup;
    });
    google.maps.event.addListener(popup, "closeclick", function() {
    map.panTo(center);
    currentPopup = null;
    });
    }

    function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {

    center: new google.maps.LatLng(0, 0),
    zoom: 14,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: true,
    mapTypeControlOptions: {
    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
    },
    navigationControl: true,
    navigationControlOptions: {
    style: google.maps.NavigationControlStyle.ZOOM_PAN
    }
    });


    setInterval(function mapload(){

    $.ajax({
    type: "POST",
    url: 'location.php',
    // data: form_data,
    success: function(data)
    {

    // var json_obj = $.parseJSON(data);//parse JSON
    var json_obj = jQuery.parseJSON(JSON.stringify(data));
    for (var i in json_obj)
    { addMarker(json_obj[i].u_lat, json_obj[i].u_lon,"Longitude:" + json_obj[i].u_lon + "<br>" + json_obj[i].u_email + "<br>" + json_obj[i].u_name);

    }
    },
    dataType: "json"//set to JSON
    })


    },3000);

    center = bounds.getCenter();
    map.fitBounds(bounds);

    }


    setInterval(function removeMarker() {
    if (markersArray) {
    for (i=0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
    marker=null;
    }
    markersArray.length = 0;
    }
    },3000);
    </script>

    </head>
    <body onLoad="initMap()" style="margin:0px; border:0px; padding:0px;">
    <div id="map"></div>
    </body>
    </html>
    Run code snippetExpand snippet
    and the database related page :

    <?php

    $conn = mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("vsms3") or die(mysql_error());
    $data = array();
    $result = mysql_query("SELECT * FROM users")or die(mysql_error());
    while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row;
    }

    echo json_encode($data);

    //echo("addMarker($lat, $lon, '<b>$name</b><br />$desc');\n");


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •