Methods and steps to access Baidu Maps API with JavaScript

Methods and steps to access Baidu Maps API with JavaScript

1. Baidu Map API Access

1. Search Baidu Map Development Platform

2. Register a Baidu account

3. Log in and apply to become a developer

4. Select the console on the homepage of the Baidu Map Development Platform and create an application in the console

image.png

After creating the application, you can see it in the console's My Applications. The most important thing is AK, which is a special key assigned to our application by Baidu Maps. You must use the key to access the Baidu Maps API.

image.png

2. Using Baidu Map API in HTML

1. Introduce Baidu map js file in HTML

<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.0&type=webgl&ak=your key"></script>

Replace the value after ak with our own secret key.

2. Define a DIV in the web page to display the map

The DIV that displays the map must have an id attribute.

image.png

3. Display the map on the web page

Basic steps:

var map = new BMapGL.Map("container"); // Create a map instance var point = new BMapGL.Point(116.404, 39.915); // Create point coordinates by latitude and longitude of geographic location map.centerAndZoom(point, 15); // Initialize the map, set the center point coordinates and map level

Optional steps:

map.centerAndZoom(point, 15); // Initialize the map, set the center point coordinates and map levelmap.enableScrollWheelZoom(true); // Enable mouse wheel zoommap.setMapType(BMAP_EARTH_MAP); // Set the map type to earth mode

4. Add optional controls

var scaleCtrl = new BMapGL.ScaleControl(); // Add scale controlmap.addControl(scaleCtrl);
var zoomCtrl = new BMapGL.ZoomControl(); // Add zoom controlmap.addControl(zoomCtrl);
var cityCtrl = new BMapGL.CityListControl(); // Add city list controlmap.addControl(cityCtrl);
var locationControl = new BMapGL.LocationControl(); // Add positioning controlmap.addControl(locationControl);

5. Positioning function

Baidu Maps supports browser positioning and IP positioning. When browser positioning fails, IP positioning will be used by default. Browser positioning is more accurate, while IP positioning can only locate an approximate location.

Baidu Maps' built-in positioning control does not use IP positioning

 //Get the current geographic location and move the center of the map to the positioning location var geolocation = new BMapGL.Geolocation(); //Create a positioning object geolocation.getCurrentPosition(function (r) { //Call the positioning function through the positioning object, the callback function parameter r represents the positioning result if (this.getStatus() == BMAP_STATUS_SUCCESS) { //If the positioning is successful var mk = new BMapGL.Marker(r.point); //Create a marker, r is the positioning result, r.point is the current positioning location map.addOverlay(mk); //Add the marker object to the map map.panTo(r.point); //Move the map center to the positioning location // alert('Your location: ' + r.point.lng + ',' + r.point.lat);
  }
  else {
    alert('failed' + this.getStatus());
  }
});

6. Add map markers

  //Add click event to the mapmap.addEventListener("click",function(e){
  //Parameter name e map click event source //console.log(e.latlng.lng+","+e.latlng.lat);
  var mk = new BMapGL.Marker(e.latlng); //Create a marker, r is the positioning result, r.point is the current positioning location map.addOverlay(mk); //Add the marker object to the map })

7. Add click events to map markers

 //Add click event to the mapmap.addEventListener("click",function(e){
  //Parameter name e map click event source //console.log(e.latlng.lng+","+e.latlng.lat);
  var mk = new BMapGL.Marker(e.latlng);//Create a marker, r is the positioning result, r.point is the current positioning locationmk.addEventListener("click",function(){//Add a click event to the markerconsole.log(this);//this refers to the marker//Because the marker is a subtag of the map object map, when we click the marker, bubbles will appear and the click event of the map will also be triggered//You can use the stopPropagation function of the event source object to organize subsequent event bubblesevent.stopPropagation();
  });
  map.addOverlay(mk); //Add the marker object to the map})

8. Add information window

//Add information window (encapsulated function)
function addInfoWindow(content,point,width,height,title) {
  //Required parameters content and point
  //content can be either text or a label //point is the latitude and longitude of a geographic location //The following three parameters are optional var opts = {
    width: width, // information window width height: height, // information window height title: title // information window title}
  var infoWindow = new BMapGL.InfoWindow(content, opts); // Create information window object map.openInfoWindow(infoWindow, point); // Open the information window }

9. Path Planning

Driving route planning

//Driving route planning object //This object must be created after the map is loaded. It is usually placed after the map object map is created. And a web page should only be created once, otherwise the last planned path will not be cleared. driving = new BMapGL.DrivingRoute(map, { renderOptions: { map: map, autoViewport: true } });
//Use the path planning object to find the route driving.clearResults(); //Clear the last planned path from the map driving.search(startPoint, endPoint); //Start path planning, pass in the start point and end point

Bus route planning

//Bus route planning object //The creation of bus route planning object must be done after the map is loaded. It is usually placed after the map object map is created. And a web page should only be created once, otherwise the last planned route will not be cleared. transit = new BMapGL.TransitRoute(map, {
  renderOptions: { map: map },
  onSearchComplete: function (results) {
    if (transit.getStatus() != BMAP_STATUS_SUCCESS) {
      return;
    }
    //alert(results.getNumPlans());//Get the total number of bus planning schemes//Design the html template for bus route planning display here var output = '';
    for(var i=0;i<results.getNumPlans();i++){
      var plan = results.getPlan(i);
      output +='<div style="margin-top:5px; background-color:#CCC"><p>Total duration:'+plan.getDuration(true)+'</p>';//Get timeoutput += '<p>Total distance:'+plan.getDistance(true)+'</p>'; //Get distanceoutput +=plan.getDescription(true)+"</div>";
    }
    $('#result').css('display', 'block'); //#result is a div we defined ourselves. We hide it by absolute positioning. The path planning is successfully displayed. $('#result').html(output); // Put the assembled path planning HTML tag template into the #result div to display it. },
});
transit.clearResults(); // Clear the last planned route transit.search(startPoint, endPoint); // Bus route planning

10. Forward and reverse address resolution

Find location based on latitude and longitude

// Create a geocoding instance var myGeo = new BMapGL.Geocoder();      
// Get the address description based on the coordinates myGeo.getLocation(longitude and latitude coordinates, function(result){
    //funcation is a callback function that is executed only after specific geographic information is found if (result){      
      alert(result.address);      
    }      
});

Query latitude and longitude coordinates based on geographic location

//Create an address parser instance var myGeo = new BMapGL.Geocoder();
// Display the address resolution result on the map and adjust the map view myGeo.getPoint(address string (Hongqihegou, Chongqing), function(point){
    if(point){
        //point is the latitude and longitude point}else{
        alert('The address you selected did not resolve to any result!');
    }
}, optional parameter) //Optional parameter to pass in the city name. If not passed, search globally. Pass in the city name and search only in this city.

This concludes this article on the steps to access Baidu Map API with JavaScript. For more information on how to access Baidu Map with JavaScript, please search previous articles on 123WORDPRESS.COM or continue browsing the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Baidu map api application marking geographic location information (js version)
  • js calls Baidu map api and adds points and annotations on the map
  • The most comprehensive Baidu Maps JavaScript offline version development
  • Reference Baidu Map in JS and remove the Baidu Map logo and information
  • Example of using JS to automatically obtain addresses and longitude and latitude using Baidu Maps API
  • js code to get the station coordinates of the bus line through Baidu map
  • JS code to achieve Baidu map circle deletion
  • JavaScript implements Baidu map mouse sliding event display and hiding

<<:  The process of installing SVN on Ubuntu 16.04.5LTS

>>:  Analysis of a MySQL deadlock scenario example

Recommend

Sample code for implementing form validation with pure CSS

In our daily business, form validation is a very ...

Vue3 (Part 2) Integrating Ant Design Vue

Table of contents 1. Integrate Ant Design Vue 2. ...

Example test MySQL enum type

When developing a project, you will often encount...

In-depth understanding of the creation and implementation of servlets in tomcat

1. What is a servlet 1.1. Explain in official wor...

VMware 15.5 version installation Windows_Server_2008_R2 system tutorial diagram

1. Create a new virtual machine from VMware 15.5 ...

Several ways to store images in MySQL database

Usually the pictures uploaded by users need to be...

Summary of Nginx load balancing methods

To understand load balancing, you must first unde...

Detailed explanation of the basic use of centos7 firewall in linux

1. Basic use of firewalld start up: systemctl sta...

IE9beta version browser supports HTML5/CSS3

Some people say that IE9 is Microsoft's secon...

Detailed explanation of ECharts mouse event processing method

An event is an action performed by the user or th...

25 Examples of Using Circular Elements in Web Design

Today, this post lists some great examples of circ...

Implementation of CSS circular hollowing (coupon background image)

This article mainly introduces CSS circular hollo...