如何将JavaScript代码获取的经纬度存储到MySQLi数据库中
Got it, let's walk through exactly how to save those latitude and longitude values from your Google Maps JavaScript code into a MySQLi database. I'll break this down into clear, actionable steps, starting with filling in the gaps in your existing code.
First, you'll need a table to store the coordinates. Run this SQL query in your MySQL database to create it:
CREATE TABLE map_coordinates ( id INT AUTO_INCREMENT PRIMARY KEY, latitude DECIMAL(10,8) NOT NULL, longitude DECIMAL(11,8) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
This table will track each coordinate entry with a unique ID, the lat/lng values, and a timestamp for when it was saved.
Let's finish your initialize() function and add code to send coordinates to a PHP backend—both the initial map center and any updates when the user pans the map:
let map; let marker; function initialize() { const myLatlng = new google.maps.LatLng(26.329086, 50.227570); const myOptions = { zoom: 12, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("gmap"), myOptions); marker = new google.maps.Marker({ position: myLatlng, map: map }); // Send the initial coordinates to the backend right away saveCoordinates(myLatlng.lat(), myLatlng.lng()); // Listen for when the user pans the map (center changes) google.maps.event.addListener(map, 'center_changed', function() { const newCenter = map.getCenter(); // Move the marker to match the new map center marker.setPosition(newCenter); // Send the updated coordinates to the backend saveCoordinates(newCenter.lat(), newCenter.lng()); }); } // Helper function to send coordinates via AJAX function saveCoordinates(lat, lng) { // Use the native Fetch API (no jQuery needed) fetch('save_coords.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `latitude=${encodeURIComponent(lat)}&longitude=${encodeURIComponent(lng)}` }) .then(response => response.text()) .then(data => { console.log('Server response:', data); // You can add success/error messages here for the user if needed }) .catch(error => { console.error('Error sending coordinates:', error); }); } // Initialize the map when the page finishes loading window.onload = initialize;
Create a file named save_coords.php—this will receive the coordinates from the frontend, validate them, and insert them into your database. Replace the database credentials with your own:
<?php // Database connection details $servername = "localhost"; $username = "your_db_username"; $password = "your_db_password"; $dbname = "your_db_name"; // Create MySQLi connection $conn = new mysqli($servername, $username, $password, $dbname); // Check if the connection failed if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Sanitize and validate input (prevent bad data) $latitude = isset($_POST['latitude']) ? floatval($_POST['latitude']) : null; $longitude = isset($_POST['longitude']) ? floatval($_POST['longitude']) : null; // Make sure we have valid coordinates if ($latitude && $longitude && $latitude >= -90 && $latitude <= 90 && $longitude >= -180 && $longitude <= 180) { // Use prepared statements to prevent SQL injection (critical!) $stmt = $conn->prepare("INSERT INTO map_coordinates (latitude, longitude) VALUES (?, ?)"); $stmt->bind_param("dd", $latitude, $longitude); // "dd" = two decimal values if ($stmt->execute()) { echo "Coordinates saved successfully! Entry ID: " . $stmt->insert_id; } else { echo "Error saving coordinates: " . $stmt->error; } $stmt->close(); } else { echo "Invalid latitude or longitude values. Please check the input."; } // Close the database connection $conn->close(); ?>
- SQL Injection Protection: We're using prepared statements with
bind_param—never directly insert user input into SQL queries, as that's a huge security risk. - Validation: The PHP code checks that coordinates are within valid ranges (latitude: -90 to 90, longitude: -180 to 180) to avoid storing garbage data.
- HTTPS: If your site is live, use HTTPS to encrypt the data being sent between the frontend and backend.
- Error Handling: The example has basic error handling, but you can expand it to show user-friendly messages (like a success alert) instead of just logging to the console.
内容的提问来源于stack exchange,提问作者Mohammed Al-Enazy

