javascriptphpmysqlmapboxmapbox-marker

Mapbox JS - Fetching Longitude and Latitude from PHP MySql


RESOLVED - SEE ANSWER BELOW

I have a MySql database called 'locationLogs' and a table called 'locations'. I have a page called map.php which shows a map (using Mapbox GLJS API). I then want to add a marker to every one of the locations in 'locations' table. The table consists of 'id', 'longitude' and 'latitude'. I then was using a while loop to attempt this. However, when going to the page, it just shows blank and doesn't load the map or anything. My code for the page is below.

<html lang='en'>
<head>
    <meta charset='utf-8' />
    <title>Live Map</title>
    <meta name='viewport' content='width=device-width, initial-scale=1' />
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v2.9.2/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v2.9.2/mapbox-gl.css' rel='stylesheet' />
    <style>
      body {
        margin: 0;
        padding: 0;
      }

      #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
      }
      .marker {
  background-image: url('mapbox-icon.png');
  background-size: cover;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  cursor: pointer;
}

    </style>
</head>
<body>

<div id='map'></div>

<script>

mapboxgl.accessToken = 'MY_ACCESS_TOKEN';

const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/light-v10',
  center: [-96, 37.8],
  zoom: 3
});

// code from the next step will go here!
<?php

$conn = mysql_connect("localhost", "DB_USER", "DB_PASS");

if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}

if (!mysql_select_db("locationLogs")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}

$sql = "SELECT *
        FROM locations";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

?>


const geojson = {
  type: 'FeatureCollection',
  features: [
      <?php
      while ($row = mysql_fetch_assoc($result)) {
    echo '
    {
        type: "Feature",
        geometry: {
            type: "Point",
            coordintes: [' . $row['longitude'] . ', ' . $row['latitude'] . ']
        },
        properties {
            title: "Location",
            description: "A cool location",
        }
    },';
    
}

mysql_free_result($result);
?>
  ]
};

// add markers to map
for (const feature of geojson.features) {
  // create a HTML element for each feature
  const el = document.createElement('div');
  el.className = 'marker';

  // make a marker for each feature and add to the map
  new mapboxgl.Marker(el).setLngLat(feature.geometry.coordinates).addTo(map);
}


</script>

</body>
</html>

Solution

  • I had to re-code a lot of this for it to work. I will attach the full code file below. The database structure is:

    TABLE: location

    id longitude latitude displayName displayDescription

    ?>
    <!DOCTYPE html>
    <html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Live Map</title>
        <meta name='viewport' content='width=device-width, initial-scale=1' />
        <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
        <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v2.9.2/mapbox-gl.js'></script>
        <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v2.9.2/mapbox-gl.css' rel='stylesheet' />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <style>
          body {
            margin: 0;
            padding: 0;
          }
    
          #map {
            position: absolute;
            top: 0;
            bottom: 0;
            width: 100%;
          }
          .marker {
      background-image: url('mapbox-icon.png');
      background-size: cover;
      width: 50px;
      height: 50px;
      border-radius: 50%;
      cursor: pointer;
    }
    .mapboxgl-popup {
      max-width: 200px;
    }
    
    .mapboxgl-popup-content {
      text-align: center;
      font-family: 'Open Sans', sans-serif;
    }
    
        </style>
    </head>
    <body>
    
    <div id='map'></div>
    
    <script>
    
    mapboxgl.accessToken = 'ACCESS_TOKEN';
    
    const map = new mapboxgl.Map({
      container: 'map',
      //style: 'mapbox://styles/mapbox/streets-v11',
      style: 'mapbox://styles/ethan-php/cl5v2t7fe000m14me1ihgd3z2',
      center: [-0.2792139521586705, 51.94498751258732],
      zoom: 9
    });
    // Add geolocate control to the map.
    map.addControl(
    new mapboxgl.GeolocateControl({
    positionOptions: {
    enableHighAccuracy: true
    },
    // When active the map will receive updates to the device's location as it changes.
    trackUserLocation: true,
    // Draw an arrow next to the location dot to indicate which direction the device is heading.
    showUserHeading: true
    })
    );
    
    // Adding markers below >>>
    </script>
    <?php
    
    $dbhost = 'localhost';
             $dbuser = 'DB_USER';
             $dbpass = 'DB_PASS';
             $dbname = 'DB_NAME';
             $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
             
             if($mysqli->connect_errno ) {
                printf("Connect failed: %s<br />", $mysqli->connect_error);
                exit();
             }
             printf('Connected successfully.<br />');
             $sql = "SELECT * FROM location";
             
             $result = $mysqli->query($sql);
               
             if ($result->num_rows > 0) {
             } else {
                printf('Unexpected Error. DB did not return enough values for a successful export.<br />');
             }
    
    ?>
    
    <script>
    
    const geojson = {
      type: 'FeatureCollection',
      features: [
          <?php
           while ($row = mysqli_fetch_assoc($result)) {
               $displayName = $row['displayName'];
               $displayDescription = $row['displayDescription'];
               ?>
            {
                type: "Feature",
                geometry: {
                    type: "Point",
                    coordinates: [<?php echo $row['longitude']; ?>, <?php echo $row['latitude']; ?>]
                },
                properties: {
                    title: "<?php echo $displayName; ?>",
                    description: "<?php echo $displayDescription; ?>"
                }
            },
          <?php
        
    }
    
    mysqli_free_result($result);
    $mysqli->close();
    ?>
      ]
    };
    
    // add markers to map
    // Popups and Display Details
    for (const feature of geojson.features) {
    // create a HTML element for each feature
    const el = document.createElement('div');
    el.className = 'marker';
     
    // make a marker for each feature and add it to the map
    new mapboxgl.Marker(el)
    .setLngLat(feature.geometry.coordinates)
    .setPopup(
    new mapboxgl.Popup({ offset: 25 }) // add popups
    .setHTML(
    `<h3>${feature.properties.title}</h3><p>${feature.properties.description}</p>`
    )
    )
    .addTo(map);
    }
    </script>
    
    </body>
    </html>