takeaway


I will not repeat the powerful functions of Baidu Map here. This article is just an introduction to baidu Map JavaScript API, hoping to be helpful to your friends. Here is the git address of this article. First of all, borrow a sentence from the official website to introduce Baidu Map JavaScript API:

Baidu Map JavaScript API is a set of application programming interface written by JavaScript language, which can help you build a rich and interactive map application in the website. It supports PC and mobile browser based map application development, and supports HTML5 features of map development.

!!!!!!!!! This article is based on the official documentation of the more basic, suitable for the beginning of the example to write, feel mind partners can choose to quit ha, but still a little glance, ha ha, let’s start ~~


Preparation before


1. Register

Before using Baidu Map, users must first have their own Baidu account, apply to register as a Baidu developer, and then create an application, which can obtain a unique service key (AK), and then use relevant services.

The specific process is as follows:

2. Create an application

3. Get our AK

After the above 3 steps, I think everyone has their own AK, so, next I will use React+webpack as the technology stack to write, all changes are the same, Vue friends or friends using other technology stack can learn from it, let’s start.


Hello Baidu Map


1.crate-react-app

React official also provides a very convenient scaffolding tool, so I will not elaborate on it here. After all, this article is not focused on this, and I may write a separate article if I have the opportunity in the future


create-react-app baiduMap

cd baiduMap

npm start

Copy the code

2. Configuration webpack

The main reason for configuring WebPack is to solve the BMap error. BMap is not defined. It is recommended to use WebPack as the main solution, that is, to access require through the externals attribute in the WebPack output object.


externals:{
    'BMap':'BMap'
}

Copy the code

The externals function of Webpack can be summarized as follows: 1. Dependencies written to externals will not be packaged into the final bundle. 2. Although it won’t be packaged, you can still introduce these dependencies in a modular way at runtime, such as commonJS,AMD,ES6 import, etc


3. Introduce Baidu Map API file

Introduced in the HTML template of Webpack


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

Copy the code


4. Create map container elements


<div id = "mapContent" style={{ height: '100vh', width: '100%' }}></div>

Copy the code


5. Create map instances

// Import BMap from'BMap'; .componentDidMount() {
    const map = new BMap.Map("mapContent"); Const point = new map.point (116.404, 39.915); // Create map instance const point = new map.point (116.404, 39.915); CenterAndZoom (point, 15); }Copy the code

6. Implementation

After the above steps, we can come out of a very simple map out, 😄, is really simple, give you a look at the effect

Well, see here, partners are not interested in the map, we then look down, there are more interesting things waiting for you behind 😜


Baidu Map go!


This part is the main function of Baidu Map, here to show partners in detail, can be modified according to their own needs.


1. Set the center point

There are two main ways to set the center point: 1. Const point = new map.point (116.404, 39.915); // Create point const point = new map.point (116.404, 39.915); map.centerAndZoom(point, 12); 2. According to the city name. // Use the city name as the center point.'tianjin', 12);

Copy the code


2. Set the Zoom value

Var map = new map.map () var map = new map.map ()"mapContent",{minZoom:4,maxZoom:8});

map.centerAndZoom('tianjin', 12); // 12 refers to the default zoom levelCopy the code


3. Set up a zoomable map

/ / the default map is only can drag the mouse, the mouse wheel will not modify the map Zoom value. EnableScrollWheelZoom (true);

Copy the code


4. Add map controls

Var mapType = new map. MapTypeControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_HYBRID_MAP], anchor: BMAP_ANCHOR_TOP_LEFT } ); Var overView = new map.overviewMapControl (); // scale var top_left_control = new map. ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT}); NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT, anchor: BMAP_ANCHOR_TOP_RIGHT, anchor: BMAP_ANCHOR_TOP_RIGHT, anchor:type: BMAP_NAVIGATION_CONTROL_SMALL});

map.addControl(mapType); 
map.addControl(overView);
map.addControl(top_left_control);  
map.addControl(top_left_navigation); 

Copy the code


5. Add annotation points

So this is some of the data that we’re using here

Const data = [{lon: 116.304854, lat:39.921988, address:'location 1',
    people: 'zhou yuan'.doThing: "Beat up the Shepherd Zhao.", {lon: 116.417824, lat:39.921910, address:'2',
    people: Lines' killings'.doThing: 'Sleeping Ice Coffin'}, {LON: 116.517777, lat:39.821999, address:'place 3',
    people: 'swallow swallow'.doThing: 'Death Experience'}];Copy the code

for(var i=0; i<data.length; i++){ var marker = new BMap.Marker(new BMap.Point(data[i].lon,data[i].lat)); Var content = [data[I].address,data[I].people,data[I].dothing]; map.addOverlay(marker); // Add annotations to the map}Copy the code

6. Add events

Often encountered in actual projects, click on the label point to pop up some information about the point, let’s try it here


for(var i=0; i<data.length; i++){ var marker = new BMap.Marker(new BMap.Point(data[i].lon,data[i].lat)); Var content = [data[I].address,data[I].people,data[I].dothing]; map.addOverlay(marker); This.addclickhandler (Content,marker, map); //addClickHandler method addClickHandler = (Content,marker, map) => {const that = this; marker.addEventListener("click".function(e){ that.openInfo(content,e, map)} ); } // openInfo = (content,e, map) => {const opts = {width: 250, // information window width height: 120, // Info window height:"Message window"// Info window titleenableMessage:true// Set to allow window to send SMS}; var p = e.target; var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat); Var infoWindow = new map. infoWindow (' <div> location:${content[0]}<br /> Characters:${content[1]}<br /> Events:${content[2]}<br /> </div> ` ,opts); OpenInfoWindow (infoWindow,point); // Open info window}Copy the code

Can achieve the effect, small partners can be free to play their own style oh 😯

7. Address resolution

Address resolution is the ability to convert a specific address into latitude and longitude

var myGeo = new BMap.Geocoder(); MyGeo. GetPoint (val, val) myGeo. GetPoint (val, val) myGeo.function(point){    

    if(point) { map.centerAndZoom(point, 16); map.addOverlay(new BMap.Marker(point)); }});Copy the code

8. Reverse address resolution

Reverse address resolution is to convert the longitude and latitude into a detailed address, which is divided into two types: 1. Specify the longitude and latitude to obtain the address 2. Mouse click on the map to obtain the address

Specify latitude and longitude to get the address

var myGeo = new BMap.Geocoder(); MyGeo. GetLocation (new map.point (116.364, 39.993),function(result){      
    if(result){ alert(result.address); }});Copy the code

Click the mouse map to obtain the address (local and local details are not the same, some can check the streets, some can check the counties)


var geoc = new BMap.Geocoder();    
map.addEventListener("click".function(e){        
var pt = e.point;
geoc.getLocation(pt, function(rs){
    var addComp = rs.addressComponents;
    alert(addComp.province + "," + addComp.city + "," + addComp.district + "," + addComp.street + "," + addComp.streetNumber);
});       

Copy the code

Baidu map is the most powerful place is planning, whether driving planning, walking planning, etc., are the most common place in our daily life, here is a driving planning.

9. Driving planning


var driving = new BMap.DrivingRoute(map, { 
    renderOptions: { 
        map: map, 
        autoViewport: true,
        panel: document.querySelector('r-reslut')}}); Var start = new map. Point(startPoint[0], startPoint[1]); Var end = new map. Point(endPoint[0], endPoint[1]); var end = new map. Point(endPoint[0], endPoint[1]); driving.search(start, end);Copy the code

All is me to baidu map of a small, simple operation, actually baidu map and there are many many interesting features, here at enmity with you said, if friends feel interesting, you can go to have a look at the map of baidu’s website, click here, in this paper, if there is any mistake, welcome to correct me in the comments section, if this article to help to you, Like 👍 and follow us at 😀.


Recommended reading

  • Oh, my god, this is inheritance!
  • Mom doesn’t have to worry about me using ECharts anymore