如何点击按钮从数据库获取经纬度更新地图标记位置(无页面刷新)
Solution: Update Marker Position Without Page Refresh
Alright, let's get your marker updating dynamically without reloading the whole page. The key here is to use AJAX to fetch the latest coordinates from your database in the background, then update the marker directly with JavaScript. Here's how to implement it:
Step 1: Create a Separate PHP API Endpoint
First, we'll make a dedicated PHP file to return the latest latitude and longitude as JSON. This lets your JavaScript request just the data it needs, not the whole page.
Create a file named get_latest_coords.php:
<?php include 'db_connect.php'; // Query for the latest soldier entry $query = "SELECT latitude, longitude, pulse FROM soldier ORDER BY id DESC LIMIT 1"; $result = mysqli_query($connection, $query); if ($result && mysqli_num_rows($result) == 1) { $row = mysqli_fetch_assoc($result); // Return data as JSON echo json_encode([ 'latitude' => (float)$row['latitude'], 'longitude' => (float)$row['longitude'], 'pulse' => $row['pulse'] ]); } else { // Return error if no data found http_response_code(404); echo json_encode(['error' => 'No coordinates found']); } mysqli_close($connection); ?>
Step 2: Modify Your Main Page Code
Next, update your main page to:
- Make the
markervariable global (so we can access it later to update its position) - Replace the page reload button with an AJAX call to our new endpoint
- Add a function to fetch and update the marker position
Here's the updated main page code:
<?php include 'db_connect.php'; // Fetch initial coordinates for map load $query = "SELECT * FROM soldier ORDER BY id DESC LIMIT 1 "; $result = mysqli_query($connection,$query); $row = mysqli_fetch_assoc($result); $count = mysqli_num_rows($result); $lat_d = $long_d = $pulse = null; if($count == 1) { $lat_d = $row['latitude']; $long_d = $row['longitude']; $pulse = $row['pulse']; } else { echo "failure"; } ?> <div class="container"> <center class="container"> <center><h1>Geo-Location</h1></center> <div id="map"></div> <div class="two-mid-button d-flex justify-content-center mt-lg-5 mt-md-4 mt-sm-4 mt-3"> <div class="view-buttn"> <!-- Changed onClick to call our update function --> <button class="button" onClick="updateMarkerPosition()">Refresh Marker</button> </div> </div> </div> <script> var map; var marker; // Global variable so we can update it later function initMap() { var myLatLng = {lat: <?php echo $lat_d; ?>, lng: <?php echo $long_d; ?>}; map = new google.maps.Map(document.getElementById('map'), { center: myLatLng, zoom: 10 }); // Initialize marker and assign to global variable marker = new google.maps.Marker({ position: myLatLng, map: map, title: 'Soldier Location' }); } // Function to fetch latest coords and update marker function updateMarkerPosition() { // Use fetch API (modern alternative to XMLHttpRequest) fetch('get_latest_coords.php') .then(response => { if (!response.ok) { throw new Error('Failed to fetch coordinates'); } return response.json(); }) .then(data => { if (data.error) { alert(data.error); return; } // Create new LatLng object with fresh coords var newPosition = new google.maps.LatLng(data.latitude, data.longitude); // Update marker position marker.setPosition(newPosition); // Optional: Center map on new position map.panTo(newPosition); // Optional: Update pulse display if needed console.log("Current pulse: " + data.pulse); }) .catch(error => { console.error('Error:', error); alert('Failed to update marker position'); }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBk3R_ceCa_Qz9_7-6rLVxACwyw27HP7XU&callback=initMap" async defer></script>
Key Changes Explained
- Global Marker Variable: By declaring
var markeroutside theinitMapfunction, we can access it in theupdateMarkerPositionfunction to modify its position. - AJAX with Fetch API: The
fetchfunction sends a background request toget_latest_coords.phpto get the newest coordinates without reloading the page. - JSON Response: The PHP endpoint returns data in JSON format, which is easy for JavaScript to parse and use.
- Marker Update: Using
marker.setPosition()lets us move the existing marker instead of creating a new one each time.
内容的提问来源于stack exchange,提问作者dockerLearner
相关产品推荐
相关产品推荐

