Home > Database > Mysql Tutorial > body text

How to implement a simple map marking function using MySQL and JavaScript

PHPz
Release: 2023-09-22 08:10:42
Original
949 people have browsed it

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:

  1. MySQL database: used to store the location information marked on the map.
  2. Some basic front-end technology tools, such as HTML, CSS and JavaScript.
  3. A basic server environment, such as Apache or Nginx, is used to run our code.

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;
Copy after login

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.

  1. HTML code
    In the HTML code, we need a map container to display the map and add an "Add Marker" button for adding new markers. For example:
Copy after login
  1. JavaScript code
    In the JavaScript code, we need to use the map API to load the map and implement the function of adding markers. Here we use the Google Maps API to demonstrate. First, we need to add a
    Copy after login

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);
}
Copy after login

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.

  1. Saving Markers
    We can use PHP to write server-side code to save markers. Create a file named "save_marker.php" and write the following code:
query($query);

// 关闭数据库连接
$mysqli->close();
?>
Copy after login
  1. Get the marker
    Similarly, we can use PHP to write server-side code to get the marker data. Create a file named "get_markers.php" and write the following code:
query($query);

// 构建标记数组
$markers = array();
while ($row = $result->fetch_assoc()) {
  $markers[] = $row;
}

// 返回标记数据
echo json_encode($markers);

// 关闭数据库连接
$mysqli->close();
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!