Home >Database >Mysql Tutorial >How to implement a simple map marking function using MySQL and JavaScript
How to use MySQL and JavaScript to implement a simple map marking function
The map marking function is very common in modern web applications. It can be used to mark specific locations, Display location information or display geographic data, etc. In this article, we'll cover how to write a simple map marker function using a MySQL database and JavaScript, and provide specific code examples.
1. Preparation
Before we start, we need to prepare some basic environments and tools:
2. Create database and table
First, we need to create a table in the MySQL database to store the location information of map markers. We can use the following SQL statement to create a table named "markers":
CREATE TABLE `markers` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, `lat` FLOAT(10,6) NOT NULL, `lng` FLOAT(10,6) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
This table contains four fields: id, name, lat and lng. The id field is an auto-incremented primary key, the name field is used to store the name of the tag, and the lat and lng fields are used to store the latitude and longitude of the tag respectively.
3. Write the front-end code
Next, we can write the front-end HTML and JavaScript code to implement the map marking function.
<div id="map"></div> <button onclick="addMarker()">添加标记</button>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
Then, in JavaScript code, we can write the following code:
// 初始化地图 function initMap() { // 创建地图对象 var map = new google.maps.Map(document.getElementById('map'), { center: {lat: 0, lng: 0}, zoom: 2 }); // 加载标记 loadMarkers(map); } // 加载标记 function loadMarkers(map) { // 发送异步请求获取标记数据 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // 解析并显示标记 var markers = JSON.parse(xhr.responseText); for (var i = 0; i < markers.length; i++) { var marker = new google.maps.Marker({ position: {lat: markers[i].lat, lng: markers[i].lng}, map: map, title: markers[i].name }); } } }; xhr.open('GET', 'get_markers.php', true); xhr.send(); } // 添加标记 function addMarker() { // 获取标记的名称、纬度和经度 var name = prompt('请输入标记的名称:'); var lat = parseFloat(prompt('请输入标记的纬度:')); var lng = parseFloat(prompt('请输入标记的经度:')); // 创建地图对象 var map = new google.maps.Map(document.getElementById('map')); // 创建标记对象 var marker = new google.maps.Marker({ position: {lat: lat, lng: lng}, map: map, title: name }); // 将标记保存到数据库 saveMarker(name, lat, lng); } // 保存标记 function saveMarker(name, lat, lng) { // 发送异步请求将标记保存到数据库 var xhr = new XMLHttpRequest(); xhr.open('POST', 'save_marker.php', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send('name=' + name + '&lat=' + lat + '&lng=' + lng); }
In the above code, we first use the initMap() function to initialize the map and call loadMarkers () function loads existing tags. The loadMarkers() function sends an asynchronous request to the server, obtains marker data, and displays the markers on the map using the Google Maps API.
In the addMarker() function, we use the prompt() function to get the marker name, latitude and longitude entered by the user, and use the Google Maps API to add the marker on the map. Then, call the saveMarker() function to send an asynchronous request to save the marker to the database.
4. Write server-side code
Finally, we need to write server-side code to handle the client's request and save the tag data to the database.
<?php // 获取标记的名称、纬度和经度 $name = $_POST['name']; $lat = $_POST['lat']; $lng = $_POST['lng']; // 连接数据库 $mysqli = new mysqli('localhost', 'username', 'password', 'your_database_name'); // 插入数据到数据库 $query = "INSERT INTO markers (name, lat, lng) VALUES ('$name', '$lat', '$lng')"; $mysqli->query($query); // 关闭数据库连接 $mysqli->close(); ?>
<?php // 连接数据库 $mysqli = new mysqli('localhost', 'username', 'password', 'your_database_name'); // 查询数据库中的标记数据 $query = "SELECT * FROM markers"; $result = $mysqli->query($query); // 构建标记数组 $markers = array(); while ($row = $result->fetch_assoc()) { $markers[] = $row; } // 返回标记数据 echo json_encode($markers); // 关闭数据库连接 $mysqli->close(); ?>
In the above code, we first connect to the MySQL database, and then write "save_marker.php" respectively and "get_markers.php" to save markers to the database and get marker data.
5. Test run
After completing the above preparations, we can deploy the relevant files to the server and access the HTML files in the browser to see the page with map marking function .
You can successfully add a new marker on the map by clicking the "Add Marker" button and entering the name, latitude and longitude. At the same time, the marked data will be saved to the MySQL database.
Summary
In this article, we introduced how to write a simple map marker function using a MySQL database and JavaScript, and provided specific code examples. Through this example, we can learn how to use MySQL to store geographic data, and how to use JavaScript and the Google Maps API to implement map marking functions. I hope it will be helpful for developing map-related applications.
The above is the detailed content of How to implement a simple map marking function using MySQL and JavaScript. For more information, please follow other related articles on the PHP Chinese website!