Javascript смещение в пределах al oop и выход не работает должным образом - PullRequest
0 голосов
/ 02 мая 2020

Функция запускается через обратный вызов после загрузки карты Google, однако заголовок, примененный в функции draw(), представляет собой только значение последней записи в массиве, эта последняя дата затем применяется ко всем маркерам, а не только соответствующие.

Часть, которая меня озадачила, что я применил ту же идею, чтобы получить markerCoords, но это прекрасно работает.

<!DOCTYPE html>
<html>
<head>
    <title>Live Illness Mapper</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <link rel="stylesheet" href="CSS/styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
    <script src="JS/jquery-3.5.0.js"></script>
    <script src="JS/script.js"></script>
</head>
<body>
<!--  
 <button onclick="window.location.href = 'submit.html';"id="submBut" type="button">Report Illness</button> 
  -->
  <button class="btn" type="button" button onclick="$('#menu').toggle();">Toggle Buttons</button>
    <div id="menu">
        <a href="submit.html"><img class="navBtns" src="images/UI/AddIllness.png" alt="Add Illness"></a>
        <a href="illnessTable.php"><img class="navBtns" src="images/UI/RemoveIllness.png" alt="Remove Illness"></a>
        <a href="Form_for_occurrence.php"><img class="navBtns" src="images/UI/ReportAffliction.png" alt="Report Affliction"></a>
        <a href="Trends.html"><img class="navBtns" src="images/UI/Trends.png" alt="Trends"></a>
    </div>
    <div id="map"></div>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDoKbEbUmn1CxDuS_1BfkKijGjkqa8kgq8&callback=showOccurrences">
    </script>
    <?php
    $host = "localhost";
    $dbusername = "--------------------";
    $dbpassword = "------------";
    $dbname = "-----------";
    // Create connection
    $conn = mysqli_connect ($host, $dbusername, $dbpassword, $dbname);
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $result = mysqli_query($conn,"SELECT Postcode FROM Occurrence_Records");

    $a = array();
    while($row = mysqli_fetch_array($result)){
        $a[] = $row['Postcode'];
    }

    $result2 = mysqli_query($conn,"SELECT Date FROM Occurrence_Records");

    $b = array();
    while($row = mysqli_fetch_array($result2)){
        $b[] = $row['Date'];
    }
    mysqli_close($conn);
?>
<script>
function showOccurrences(){
    var geocoder;
    var address;
    var markerCoords;
    var locations;
    var dates;
    var recorded;
    var a = <?php echo json_encode($a); ?>;
    var b = <?php echo json_encode($b); ?>;
    console.log(a);
    console.log(b);

    var Worcester = {lat: 52.188, lng: -2.220};

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 13,
      center: Worcester
    });

    while (a.length >0 && b.length >0){ //while the postcode array still has postcodes in it
        locations = a[0]; //value of the last postcode in the array
        dates = b[0];
        geocoder = new google.maps.Geocoder();
        address = locations;
        GeocodeMarker(a[0], b[0]);
        a.shift();
        b.shift();
        console.log(locations);
        console.log(dates);


        /* FIND SOMEWHERE TO LOOP PROPERLY DATE FOR MARKERS IN CONJUNCTION WITH POSTCODE - is currently only using last date ======================================

        */
    }

    function GeocodeMarker (address, dates){
       geocoder.geocode( { 
        'address': address}, 
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            markerCoords = results[0].geometry.location;
            createMarker(markerCoords, dates);
            //console.log(results[0].geometry.location
          } else {
          alert('Click ok to add illness markers');
          }
        });
    }


    function createMarker(){
        console.log(markerCoords, dates);
        var image = 'images/Logo/virus.png';
        marker = new google.maps.Marker({
          title: dates,
          position: markerCoords,
          map: map,

          icon: image

        });
    }
}
</script>
</body>
</html>

1 Ответ

0 голосов
/ 02 мая 2020

Я бы предложил передать координаты и заголовок (текст при наведении курсора) в функции (вместо того, чтобы рассчитывать на глобальные переменные для работы).

Вам потребуются две функции:

  1. a createMarker функция (заменяет вашу draw функцию).
  2. a GeocodeMarker функция (заменяет вашу Geocoding функцию).
function createMarker(markerCoords, date){
    var image = 'images/Logo/virus.png';
    var marker = new google.maps.Marker({
          title: date,
          position: markerCoords,
          map: map,
          icon: image
    });
}
function GeocodeMarker(address, date){
  geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        markerCoords =results[0].geometry.location;
        createMarker(markerCoords, date);
      } else {
        alert("Can't geocode: "+address+", status="+status);
      }
  });
}

подтверждение концепции скрипта

фрагмент кода:

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -34.397,
      lng: 150.644
    },
    zoom: 8
  });
  showOccurrences();
}

function showOccurrences() {
  var geocoder;
  var address;
  var markerCoords;
  var locations;
  var dates;
  var recorded;
  var a = ["10007", "07102", "07649"]; // <?php echo json_encode($a); ?>;
  var b = ["1/1/2000", "2/2/2001", "3/3/2003"]; // <?php echo json_encode($b); ?>;
  console.log(a);
  console.log(b);

  var Worcester = {
    lat: 52.188,
    lng: -2.220
  };

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: Worcester
  });

  while (a.length > 0 && b.length > 0) { //while the postcode array still has postcodes in it
    locations = a[0]; //value of the last postcode in the array
    dates = b[0];
    geocoder = new google.maps.Geocoder();
    address = locations;
    GeocodeMarker(a[0], b[0]);
    a.shift();
    b.shift();
    console.log(locations);
    console.log(dates);
  }
  var bounds = new google.maps.LatLngBounds();

  function GeocodeMarker(address, date) {
    geocoder.geocode({
      'address': address
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        bounds.extend(results[0].geometry.location);
        map.fitBounds(bounds);
        markerCoords = results[0].geometry.location;
        createMarker(markerCoords, date);
      } else {
        alert("Can't geocode: "+address+", status="+status);
      }
    });
  }


  function createMarker(markerCoords, date) {
    console.log(markerCoords, date);
    var image = 'images/Logo/virus.png';
    marker = new google.maps.Marker({
      title: date,
      position: markerCoords,
      map: map,
    });
  }
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...