Baidu lbs Map Web-side development practice

Source: Internet
Author: User
Tags button type event listener

Baidu Map API is available to developers in open form, completely free of charge and can be used directly without commercial authorization.
This tutorial we mainly explain the map of Baidu map display, local search, inverse/geocoding, covering, city list and other key functions.

0. Display

Here's a look:

    1. Click on the Location tab to show Baidu map, if the store set up a geographical location, then direct positioning; otherwise, the default address location via IP (this need to improve, I am in Luoyang, but according to the IP location to Zhengzhou).
    2. With the city list and local search, you can directly navigate to the desired address, find the coordinates, will have a red position on the map marker.
    3. Right-marker, you can set the location of the AJAX request.

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

1. Loading Baidu Map asynchronously

Before using the Baidu map, you need to apply for an application key (AK).

The tab of the map is constructed 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 " >Location</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 Jacob Black '; ></div></div>

Explain:

    1. The version of the map in Map_url is the key that the 2.0,ak parameter is configured in the background, callback to set the asynchronous loading of the map.
    2. Lbs_point is the location coordinate of the store (eg:112.42757,34.630966).
    3. Map-markers is the div that shows the map.

JS for asynchronous loading:

$(' 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 map");//encapsulated with Console.log$script = $ (' <script id= ' bdmapscript ' ></script> '). attr ("src", $tab. attr ("Map_url"). AppendTo ("Body"); }}); function initializemap() {    varMap =NewBmap.map (' Map-markers '); ...}

Explain:

    1. Shown.bs.tab is the event listener for the Bootstrap tab switch.
    2. By assigning a value src to the script, the API for Baidu maps can be loaded asynchronously.
    3. The Initializemap method is the key execution method after the first load of the map, and we then explain the details in a step-by-step manner.
2. Initialize the location
//The store locator address (eg:112.42757,34.630966) that is passed on the pagevarLbs_point = $ ("#lbs_point"). Val ();if(Lbs_point && Lbs_point.indexof (",") != -1) {varPoints = Lbs_point.split (",");varPoint =NewBmap.point (points[0], points[1]); Map.centerandzoom (Point, the); Addmarker (point);//After introduction}Else{//without coordinates, use the "Local IP location" service of Baidu map     function myfun(Result) {        varPoint = Result.center; Map.centerandzoom (Point, the); Addmarker (point);//After introduction}varMycity =NewBmap.localcity (); Mycity.get (myfun);}

Explain:

    1. Lbs_point is the location of the store, and the point object allows you to set the center of the map directly.
    2. When the store first locates, according to the Localcity object, obtains the center point which the IP locates.
    3. Once the Centerandzoom method is executed, the map can be displayed; The first parameter is the center coordinate point, the second parameter is the map zoom level, currently set to 15; This method is especially critical, and the map is not displayed without the method.
3. Add the overlay of point marker (red that water droplet, inverted)
 function addmarker(point) {    //Create a right-click menu    varUpdatelocationmarker = function(e, EE, marker) {Yunm.debug (point); Ajaxtoupdateloaction (point);//Save store locator address, then introduce};varMarker =NewBmap.marker (point);//Create annotationsMap.addoverlay (marker);//Add labels to the map    //DragMarker.enabledragging (); Marker.addeventlistener ("Dragend", function(e) {Point = E.point; });//Right-click menu    varMarkermenu =NewBmap.contextmenu ();    Marker.addcontextmenu (Markermenu); Markermenu.additem (NewBmap.menuitem (' Set as store address ', Updatelocationmarker.bind (marker)));}

Explain:

    1. Updatelocationmarker is the right-click menu event, and the content is executed in the Ajaxtoupdateloaction method. Later introduced.
    2. Marker is a label for Point, which is a covering; after setting up drag and drop, you can reposition the store address by dragging and dragging.
    3. Markermenu is the right-click menu.
4. Add positioning controls
varnew BMap.GeolocationControl();geolocationControl.addEventListener("locationSuccess"function(e) {    map.clearOverlays();// 移除所有覆盖物    addMarker(e.point);// 重新添加定位后的坐标点});geolocationControl.addEventListener("locationError"function(e) {    // 定位失败事件    YUNM.debug(e.message);});map.addControl(geolocationControl);
5. City List
varnew BMap.Size(1020);map.addControl(new BMap.CityListControl({    anchor : BMAP_ANCHOR_TOP_LEFT,// 显示在地图的左上角    offset : size,// 偏移}));

This component is very practical, but the need to spit groove is Baidu is very unkind, detailed can see the contrast.

List of cities that the API provides:

Baidu Map of the city list (see also Putian):

Use someone's mouth short, do not say.

6. Customizing the Local search box
//Define a control class, Local search box function searchcontrol() {    //default docking position and offset     This. Defaultanchor = Bmap_anchor_top_left; This. Defaultoffset =NewBmap.size (Ten, -);}//via JavaScript's prototype property inherited from Bmap.controlSearchcontrol.prototype =NewBmap.control ();//The custom control must implement its own initialize method and return the DOM element of the control//Create a DIV element in this method as a container for the control and add it to the map containerSearchControl.prototype.initialize = function(map) {    //Create a DOM element    varMap_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 ();//Clear all overlays on the map         function myfun() {            varpp = Local.getresults (). Getpoi (0). Point;//Get the results of the first smart searchMap.centerandzoom (PP, the);        Addmarker (PP); }varLocal =NewBmap.localsearch (map, {//Smart SearchOnsearchcomplete:myfun}); Local.search (Map_searchbox.find ("Input"). Val ());//Retrieve input keywords});//Add DOM elements to the mapMap.getcontainer (). AppendChild (Map_searchbox.get (0));//Returns the DOM element    returnMap_searchbox.get (0);};//Create ControlsvarMysearchcontrol =NewSearchControl ();//Add to mapMap.addcontrol (Mysearchcontrol);

The notes are very clear, and we will not repeat them.
Retrieve the Wang Cheng Park in Luoyang!
Luoyang Peony A world, right, this season, it is time to gather a lively!
The number of peonies in the park is not small.

7. Inverse Address Resolution

Let's take a look at two pictures:

Left-click on the coordinates, the right button on the marker to display the "Set as store Address" of the right-click menu, and then leave the menu, pop-Up confirmation dialog box.
We can see, "Henan province Luoyang Xigong District Nakasu Middle Road No. 310," this paragraph is the reverse address of point resolution.

function ajaxToUpdateLoaction(point) {    varnew BMap.Geocoder();// 逆地址解析    function(rs) {        YUNM.debug(rs.address);        $.showConfirm("您确定要将 "" 设为当前地址吗?"function() {});    });}

Well, this article first introduces this.
After the intention to introduce the Baidu map of the lbs cloud Search, please continue to pay attention.

The Silent King two public number is recruiting the writer who has the common hobby and the reader, welcome you to join Oh!

Sweep the QR code below to follow:

Baidu lbs Map Web-side development combat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.