Здесь Карты - только последний набор данных выбирается: - PullRequest
0 голосов
/ 05 апреля 2020

Итак, здесь есть два случая: Здесь Карты и Карты TomTom. Используя их JS SDK для обоих случаев.

Я пытался установить маркеры на карте, используя данные широты и долготы из моей базы данных. Мне удалось подключиться к базе данных и получить данные, а также отобразить их на карте. Код для них обоих практически одинаков. Моя единственная проблема возникает, когда существует более одного набора данных, таких как in, 2 или 3 идентификатора с 2 или 3 различными данными lat / long.

Проблема с картами Here: это выборка только последнего набора данных. Проблема с картами TomTom: усреднение всех латов и длин и выбрасывание 3-го места в целом.

Вот мой database.php

<?php

$servername = "localhost";
$username = "admin_abhisar";
$password = "Abhisar@1991";
$dbname = "admin_maps";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT lat, lng from markers ";


$result = $conn->query($sql);


if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $lat = $row ['lat'];
        $lng = $row ['lng'];
        $loc = ($lng . "," . " " . $lat . " " . ";" . " ");
        print_r($loc).""; 
    }
} 
$conn->close();
?>

Вот основной index.php, скрывающий мой Ключ API по понятным причинам:

<?php
require 'database.php';
?>
    <html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, width=device-width" />
    <script src="https://js.api.here.com/v3/3.1/mapsjs-core.js"
    type="text/javascript" charset="utf-8"></script>
    <script src="https://js.api.here.com/v3/3.1/mapsjs-service.js"
    type="text/javascript" charset="utf-8"></script>
    <script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js"
       type="text/javascript" charset="utf-8"></script>

  </head>
  <body>
    <div style="width: 100%; height: 85%" id="mapContainer"></div>
    <script>
      // Initialize the platform object:
      var platform = new H.service.Platform({
        'apikey': '<key-here>'
      });

      // Obtain the default map types from the platform object
      var maptypes = platform.createDefaultLayers();



      // Instantiate (and display) a map object:
      var map = new H.Map(
        document.getElementById('mapContainer'),
        maptypes.vector.normal.map,
        {
          zoom: 15,
          center: { lat: 19.768893, lng: 73.032100 }
        });


// Enable the event system on the map instance:
var mapEvents = new H.mapevents.MapEvents(map);

// Add event listeners:
map.addEventListener('tap', function(evt) {
    // Log 'tap' and 'mouse' events:
    console.log(evt.type, evt.currentPointer.type);
});

// Instantiate the default behavior, providing the mapEvents object:
var behavior = new H.mapevents.Behavior(mapEvents);


// Define a variable holding SVG mark-up that defines an icon image:
var svgMarkup = '<svg width="24" height="24" ' +
    'xmlns="http://www.w3.org/2000/svg">' +
    '<rect stroke="white" fill="#1b468d" x="1" y="1" width="22" ' +
    'height="22" /><text x="12" y="18" font-size="12pt" ' +
    'font-family="Arial" font-weight="bold" text-anchor="middle" ' +
    'fill="white">O</texfor( i = 0; i < markers.length; i++ ) {t></svg>';


// Create an icon, an object holding the latitude and longitude, and a marker:
var icon = new H.map.Icon(svgMarkup),
    lat = <?php echo json_encode($lat) ?>;
    lng = <?php echo json_encode($lng) ?>;
    coords = {lat: lat, lng: lng},
    marker = new H.map.Marker(coords, {icon: icon});

// Add the marker to the map and center the map at the location of the marker:
map.addObject(marker);
map.setCenter(coords);

// Add the marker to the map:


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

Что я делаю не так? Я ожидаю получить индивидуальные маркеры для отдельных мест. Любая помощь будет оценена.

Спасибо

1 Ответ

0 голосов
/ 05 апреля 2020

Ваши переменные $lat и $lng хранят только одно значение, поэтому в вашем l oop вы перезаписываете значение каждый раз. И, наконец, у вас есть только значения последней строки для обработки.

Вам нужно сохранить все ваши значения в массиве:

$coords = array() ; // store all coordinates
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $lat = $row ['lat'];
        $lng = $row ['lng'];
        $coords[] = array($lat, $lng) ; // add a new point to the global array
    }
} 

и сделать еще один l oop в разделе javascript каждый маркер отображается отдельно:

var coordinates = <?php echo json_encode($coords);?> ;
var icon = new H.map.Icon(svgMarkup);

for(let i = 0, len = coordinates.length ; i < len ; ++i)
{
    // retrieve coordinates of point i
    let lat = coordinates[i][0] ;
    let lng = coordinates[i][1] ;
    let coords = {lat: lat, lng: lng} ;

    // build marker
    let marker = new H.map.Marker(coords, {icon: icon});

    // Add the marker to the map and center the map at the location of the marker:
    map.addObject(marker);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...