Web-side Development of Baidu LBS Map

Keywords: JSP Javascript Attribute

Baidu Map API is available to developers in an open form, completely free of charge, and can be used directly without commercial authorization.
This tutorial focuses on the key functions of Baidu Map, such as map display, local search, inverse/geocoding, coverage, city list and so on.

0. Effect map display

Introduce to you:

  1. Click on the tab of the geographical location to display Baidu map. If the shop has a geographical location, locate it directly. Otherwise, locate it by default address through IP (which needs improvement, I am in Luoyang, but locate it in Zhengzhou according to IP).
  2. Through the city list and local search, you can directly locate the desired address, find the coordinates, there will be a red location marker on the map.
  3. Right-click marker to set the location of the ajax request.

ps: If you don't need these features for your project, you can skip this article.

1. Asynchronous Loading of Baidu Map

Before using Baidu Map, you need to apply for one. Application key (ak).

tab to construct the map on the jsp page.

<li class="active">
    <a href="#address" data-toggle="tab" map_url="http://api.map.baidu.com/api?v=2.0&ak=<%=Variables.baidu_map_key%>&callback=initializeMap">geographical position</a>
</li>

<div class="tab-pane active" id="address">
    <input type="hidden" id="lbs_point" value="${lbs_point}">
    <div id="map-markers" style="width: 100%; height: 470px; overflow: hidden; margin: 0; font-family: 'Microsoft YaHei';"></div>
</div>

Explain:

  1. The map version in map_url is 2.0. The ak parameter is the key configured in the background. callback sets up the asynchronous loading of the map.
  2. lbs_point is the location coordinate of the store (eg: 112.42757, 34.630966).
  3. map-markers are div s for displaying maps.

js loads asynchronously:

$('a[data-toggle="tab"][href="#address"]').on('shown.bs.tab', function(e) {
    var $tab = $(e.target);

    var $script = $("#bdmapscript");

    if ($script.size() == 0) {
        YUNM.debug("Start loading default maps");// Encapsulated console.log

        $script = $('<script id="bdmapscript"></script>').attr("src", $tab.attr("map_url")).appendTo("body");
    }

});

function initializeMap() {
    var map = new BMap.Map('map-markers');
    ...
}

Explain:

  1. Show.bs.tab is event listener for tab switching of bootstrap.
  2. By assigning src to script, the api of Baidu Map can be loaded asynchronously.
  3. The initializeMap method is the key execution method after the first loading of the map. The specific content is explained step by step.

2. Initialization of geographical location

// Store Location Address Passed on the Page (eg: 112.42757, 34.630966)
var lbs_point = $("#lbs_point").val();
if (lbs_point && lbs_point.indexOf(",") != -1) {
    var points = lbs_point.split(",");
    var point = new BMap.Point(points[0], points[1]);

    map.centerAndZoom(point, 15);

    addMarker(point);// Later on
} else {// Use Baidu Map's Local IP Location Service without Coordinates
    function myFun(result) {
        var point = result.center;
        map.centerAndZoom(point, 15);

        addMarker(point);// Later on
    }
    var myCity = new BMap.LocalCity();
    myCity.get(myFun);
}

Explain:

  1. lbs_point is the location address of the shop, and the center of the map can be set directly through the Point object.
  2. When the store locates for the first time, according to the LocalCity object, the center point is located by IP.
  3. After the central AndZoom method is executed, the map can be displayed; the first parameter is the central coordinate point, the second parameter is the zoom level of the map, which is currently set to 15; this method is particularly critical, without which the map will not be displayed.

3. Cover marker with point (red droplet, reverse)

function addMarker(point) {
    // Create a right-click menu
    var updateLocationMarker = function(e, ee, marker) {
        YUNM.debug(point);

        ajaxToUpdateLoaction(point);// Preserve the location address of the store, and then introduce it.
    };

    var marker = new BMap.Marker(point); // Create annotations
    map.addOverlay(marker); // Add annotations to maps

    // Drag and drop
    marker.enableDragging();
    marker.addEventListener("dragend", function(e) {
        point = e.point;
    });

    // Right-click menu
    var markerMenu = new BMap.ContextMenu();
    marker.addContextMenu(markerMenu);
    markerMenu.addItem(new BMap.MenuItem('Shop Address', updateLocationMarker.bind(marker)));
}

Explain:

  1. The updateLocation Marker is a right-click menu event that executes the content in the ajaxToUpdateLoaction method. Then it is introduced.
  2. marker is a mark for point, which is a cover; after dragging, the store address can be relocated by dragging.
  3. markerMenu is the right-click menu.

4. Add Location Control

var geolocationControl = new BMap.GeolocationControl();
geolocationControl.addEventListener("locationSuccess", function(e) {
    map.clearOverlays();// Remove all mulches
    addMarker(e.point);// Re-adding positioned coordinate points
});
geolocationControl.addEventListener("locationError", function(e) {
    // Locate Failure Events
    YUNM.debug(e.message);
});
map.addControl(geolocationControl);

5. City List

var size = new BMap.Size(10, 20);
map.addControl(new BMap.CityListControl({
    anchor : BMAP_ANCHOR_TOP_LEFT,// Display in the top left corner of the map
    offset : size,// deviation
}));

This component is very practical, but it is very unkind for Baidu to use Tucao.

API provides a list of cities:

Baidu Map Official Website City List (See also Putian):

Don't say anything with a short mouth.

6. Customize the local search box

// Define a control class, local search box
function SearchControl() {
    // Default parking position and offset
    this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
    this.defaultOffset = new BMap.Size(10, 50);
}

// Inheritance to BMap.Control through JavaScript's prototype attribute
SearchControl.prototype = new BMap.Control();

// A custom control must implement its initialize method and return the DOM element of the control
// In this method, create a div element as a container for the control and add it to the map container
SearchControl.prototype.initialize = function(map) {
    // Create a DOM element
    var map_searchbox = $('<div><div class="input-group input-group-sm" id="map_searchbox" style="width: 225px;">'
            + '<input class="form-control" type="text">' + '<span class="input-group-btn">'
            + ' <button type="button" class="btn btn-info btn-flat"><i class="fa fa-search"></i></button>' + '</span>' + '</div></div>');

    map_searchbox.find("button").click(function(e) {
        map.clearOverlays(); // Clean up all the covering on the map
        function myFun() {
            var pp = local.getResults().getPoi(0).point; // Get the results of the first intelligent search
            map.centerAndZoom(pp, 15);

            addMarker(pp);
        }
        var local = new BMap.LocalSearch(map, { // Intelligent Search
            onSearchComplete : myFun
        });
        local.search(map_searchbox.find("input").val());// Retrieving keywords entered
    });

    // Add DOM elements to the map
    map.getContainer().appendChild(map_searchbox.get(0));
    // Return DOM elements
    return map_searchbox.get(0);
};
// Create controls
var mysearchControl = new SearchControl();
// Add to the map
map.addControl(mysearchControl);

The annotations are well explained and will not be repeated.
Search the Royal City Park in Luoyang.
Luoyang peony is the best in the world. Yes, this season, it's time to make fun of it!
The number of peony in Wang Cheng Park is not small.

7. Reverse Address Resolution

Let's start with two pictures:

After selecting the coordinates by left-click, right-click on the marker to display the right-click menu of "Setting Store Address". Then left-click the menu and pop up the confirmation dialog box.
We can see that "No. 310 Zhongzhong Road, Xigong District, Luoyang City, Henan Province" is the reverse address of point.

function ajaxToUpdateLoaction(point) {
    var geoc = new BMap.Geocoder();// Reverse Address Resolution
    geoc.getLocation(point, function(rs) {
        YUNM.debug(rs.address);

        $.showConfirm("You are sure you want to " + rs.address + " Is it the current address?", function() {});
    });
}



Reprinted from: http://blog.csdn.net/qing_gee/article/details/70597521


Posted by PURU on Fri, 05 Jul 2019 15:32:07 -0700