Note source: Hook Education – big front end employment Training camp

Content: Notes, thoughts and experiences in the process of learning

Tip: project actual combat article resources can not be uploaded, only for reference

Develop amAP small project

Apply to amap as a developer

  • Register amap developer account: official website address
  • Create an application: Manage an application => Create an application
  • Create app keys: Different apps have different keys (Android/ios/Web/applets)

Details autonavi wechat apap SDK

  • downloadSmall program SDK
    • Essentially the SDK iswx.requestrightThe WEB services APIPackage, no matter which platform compatibility is guaranteed
    • The running environment of the applets is actually the built-in browser environment

Autonavi small program SDK part common interface

API describe
getWxLocation Get location information (via autonavi API)
getRegeo Obtain geographic description information (convert longitude and latitude into administrative division name)
getWeather For the weather information of the current location, less data is recommended to use mild weather
getPoiAround Query surrounding points of Interest (POI), such as search
getStaticmap Get static map (can’t drag)
getInputtips Get input prompt words (keyword query)
getWalkingRoute Walking Route Planning
getDrivingRoute Driving route planning
getRidingRoute Cycling Route Planning
getTransitRoute Bus and subway route planning (different from the first three parameters)

Most of the interface functions in amap’s SDK are actually the product of secondary encapsulation of the cloud API of small programs

Home access to Amap

  • Get the current location when the small program starts and save it locally
  • Copy the Autonavi SDK file into the project and create the Autonavi SDK configuration file
  • Create the Autonavi SDK instance object, write the KEY, and finally export the instance object
  • When the home page is loaded, reverse address resolution (Gaude-Getregeo) is performed to obtain the actual address
  • Write the map map component and add related properties
  • The js file on the home page contains local latitude and longitude data before parsing
  • Directly use the data returned by Autonavi for registration point data
  • Adjust the style to make the map display in full screen
  • Add bottom address bar, absolute location, use getRegeo to return data
// app.json
{
  "pages": [
    // Add a page
    "pages/home/home"."pages/index/index"."pages/logs/logs"]."window": {
    "backgroundTextStyle": "light"."navigationBarBackgroundColor": "#fff"."navigationBarTitleText": "Weixin"."navigationBarTextStyle": "black"
  },
  "style": "v2"."sitemapLocation": "sitemap.json".// Get the current location
  "permission": {
    "scope.userLocation": {
      "desc": "Trying to get location information"}},// Set the bottom navigation
  "tabBar": {
    "list": [{
      "pagePath": "pages/home/home"."text": "Home page"."iconPath": "./static/images/featured.png"."selectedIconPath": "./static/images/featured-actived.png"
    }, {
      "pagePath": "pages/index/index"."text": "Welcome"."iconPath": "./static/images/featured.png"."selectedIconPath": "./static/images/featured-actived.png"
    }, {
      "pagePath": "pages/logs/logs"."text": "Log"."iconPath": "./static/images/featured.png"."selectedIconPath": "./static/images/featured-actived.png"}}}]Copy the code
// app.js
App({
  onLaunch() {
    // Display local storage capability
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    / / login
    wx.login({
      success: res= > {
        // Send res.code to the backend for openId, sessionKey, unionId}})// Get the current location
    wx.getLocation({
      type: 'gcj02'.// Store latitude and longitude locally after success
      success (res) {
        wx.setStorageSync('latitude', res.latitude)
        wx.setStorageSync('longitude', res.longitude)
      }
     })
  },
  globalData: {
    userInfo: null}})Copy the code
// utils/amap-config.js SDK configuration for AmAP

// Introduce the Autonavi SDK
const amapfile = require('./amap-wx.130')

// Create an instance
const map = new amapfile.AMapWX({
  key: '842828a8a2bce6537a91450390dd5471'
})

/ / export
module.exports = {
  map
}
Copy the code
// pages/home/home.js

const amap = require('.. /.. /utils/amap-config')
Page({

  /** * initial data for the page */
  data: {},/** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // Store this pointer
    const that = this
    // Read local location information and store it in data
    that.setData({
      longitude: wx.getStorageSync('longitude'),
      latitude: wx.getStorageSync('latitude')})// Call gaode inverse address resolution to obtain the location information of coordinates
    amap.map.getRegeo({
      // Successful call
      success: res= > {
        console.log(res);
        // Use data as markup information
        // Set the tag to use the image
        res[0].iconPath = '/static/images/location.png'
        // Store markup data locally
        that.setData({
          markers: res
        })
      },
      // Failure Displays failure information
      fail: err= > {
        console.log(err)
      }
    })
  },

  /** * lifecycle function - listen for the page to complete the first rendering */
  onReady: function () {},/** * lifecycle function -- listens for page display */
  onShow: function () {},/** * life cycle function - listen for page hiding */
  onHide: function () {},/** * life cycle function - listen for page unload */
  onUnload: function () {},/** * page-related event handlers -- listen for user pull actions */
  onPullDownRefresh: function () {},/** * the handler for the pull-down event on the page */
  onReachBottom: function () {},/** * Users click on the upper right corner to share */
  onShareAppMessage: function () {}})Copy the code
<! --pages/home/home.wxml-->
<view class="container">
  <! -- Map component, set latitude and longitude, marker information -->
  <map class="map" name="" longitude='{{longitude}}' latitude='{{latitude}}' markers='{{markers}}' scale="14"></map>
  <! -- Bottom float position display -->
  <view class="map-text">
    <text>{{markers[0].name}}</text>
    <text>{{markers[0].desc}}</text>
    <view class="button-sp-area">
			<a class="weui-btn weui-btn_mini weui-btn_primary">button</a>
		</view>
  </view>
</view>
Copy the code
/* pages/home/home.wxss */
/* /* */
.container {
  height: 100vh;
  width: 100vw;
}

/ * * / map
.map {
  width: 100%;
  height: 100%;
}

/* Bottom text */
.map-text {
  position: relative;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  /* text-align: center; * /
}
.map-text > text {
  display: block;
  margin: 10px 20px;
}
.map-text > text:nth-child(2) {
  font-size: 14px;
  color: # 666;
}
.map-text > .button-sp-area {
  position: absolute;
  right: 20px;
  top: 50%;
  margin-top: -16px;
}
Copy the code

The input prompt

useAmap API –getInputtips()

  • Search box uses WEUI search box component, copy JS and WXML
  • Add logic to the input event and use the input to call the API to get input prompts
  • You can encapsulate this logic as a single function
  • Store the received prompt data into data
  • Use weUI’s list component to display input prompt data, only if there is prompt data
  • Iterate through the data list to create the structure
  • May conflict with the previous written text prompt, change the bottom text prompt to fixed positioning
  • Add judgment conditions, if the input content is empty, empty data, not empty data request
  • Remember that the cancel button also clears the data
/**app.wxss**/
/* Introduce WeUI */
@import './weui.wxss';

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  /* padding: 200rpx 0; * /
  box-sizing: border-box;
}
Copy the code
<! --pages/home/home.wxml-->
<view class="container">
  <! -- Top search box -->
  <view class="page__bd">
    <view class="weui-search-bar {{inputShowed ? 'weui-search-bar_focusing' : ''}}" id="searchBar">
      <form class="weui-search-bar__form">
        <view class="weui-search-bar__box">
          <i class="weui-icon-search"></i>
          <input type="text" class="weui-search-bar__input" placeholder="Search" value="{{inputVal}}"
            focus="{{inputShowed}}" bindinput="inputTyping" />
          <span class="weui-icon-clear" wx:if="{{inputVal.length > 0}}" bindtap="clearInput"></span>
        </view>
        <label class="weui-search-bar__label" bindtap="showInput">
          <i class="weui-icon-search"></i>
          <span class="weui-search-bar__text">search</span>
        </label>
      </form>
      <view class="weui-search-bar__cancel-btn" bindtap="hideInput">cancel</view>
    </view>
    <view class="weui-cells searchbar-result" wx:if="{{inputVal.length > 0}}">
      <! Create search prompt results by traversing data -->
      <view class="weui-cell weui-cell_active weui-cell_access" wx:for="{{tips}}" wx:key='{{item.id}}}'>
        <view class="weui-cell__bd weui-cell_primary">
          <view>{{item.name}}</view>
        </view>
      </view>
    </view>
  </view>
  <! -- Map component, set latitude and longitude, marker information -->
  <map class="map" name="" longitude='{{longitude}}' latitude='{{latitude}}' markers='{{markers}}' scale="14"></map>
  <! -- Bottom float position display -->
  <view class="map-text">
    <text>{{markers[0].name}}</text>
    <text>{{markers[0].desc}}</text>
    <view class="button-sp-area">
			<a class="weui-btn weui-btn_mini weui-btn_primary">button</a>
		</view>
  </view>
</view>
Copy the code
/* pages/home/home.wxss */
/* /* */
.container {
  height: 100vh;
  width: 100vw;
}

/ * * / map
.map {
  width: 100%;
  height: 100%;
}

/* Bottom text */
.map-text {
  position: relative;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  /* text-align: center; * /
}
.map-text > text {
  display: block;
  margin: 10px 20px;
}
.map-text > text:nth-child(2) {
  font-size: 14px;
  color: # 666;
}
.map-text > .button-sp-area {
  position: absolute;
  right: 20px;
  top: 50%;
  margin-top: -16px;
}

/* Search box */
.page__bd {
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
}

.searchbar-result {
  margin-top: 0;
  font-size: 12px
}

.searchbar-result .weui-cell {
  padding: 10px;
}
.searchbar-result .weui-cell__bd {
  padding: 0 0 0 20px;
  color: # 999;
}

.searchbar-result:before {
  display: none
}
Copy the code
// pages/home/home.js

const amap = require('.. /.. /utils/amap-config')
Page({

  /** * initial data for the page */
  data: {
    inputShowed: false.inputVal: ""
  },
  // Click the TV search box time event function
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  // Cancel the button click event function
  hideInput: function () {
    this.setData({
      inputVal: "".inputShowed: false
    });
  },
  // Clear the button click event function
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  // Text box input event
  inputTyping: function (e) {
    // Store input
    this.setData({
      inputVal: e.detail.value
    });
    // Call the method to get prompt data
    this.getTips(e.detail.value)
  },
  // Get input prompt data
  getTips: function (keywords) {
    // Store this pointer
    const that = this
    // Call the Gaud method to get an input reminder
    amap.map.getInputtips({
      // Enter the content
      keywords,
      // Location information
      location: that.data.longitude + ', ' + that.data.latitude,
      // called after success
      success: (res) = > {
        // If the data is successfully obtained, the data is stored
        if(res && res.tips) that.setData({tips: res.tips})
        console.log(that.data.tips); }})},/** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // Store this pointer
    const that = this
    // Read local location information and store it in data
    that.setData({
      longitude: wx.getStorageSync('longitude'),
      latitude: wx.getStorageSync('latitude')})// Call gaode inverse address resolution to obtain the location information of coordinates
    amap.map.getRegeo({
      // Successful call
      success: res= > {
        console.log(res);
        // Use data as markup information
        // Set the tag to use the image
        res[0].iconPath = '/static/images/location.png'
        // Store markup data locally
        that.setData({
          markers: res
        })
      },
      // Failure Displays failure information
      fail: err= > {
        console.log(err)
      }
    })
  },

  /** * lifecycle function - listen for the page to complete the first rendering */
  onReady: function () {},/** * lifecycle function -- listens for page display */
  onShow: function () {},/** * life cycle function - listen for page hiding */
  onHide: function () {},/** * life cycle function - listen for page unload */
  onUnload: function () {},/** * page-related event handlers -- listen for user pull actions */
  onPullDownRefresh: function () {},/** * the handler for the pull-down event on the page */
  onReachBottom: function () {},/** * Users click on the upper right corner to share */
  onShareAppMessage: function () {}})Copy the code

Look around for points of interest

Call the Map of GaudgetPoiAround()Method to obtain the data of interest points

  • Select a point: show the current point text, highlight the current point, navigate to the point (more on that later)

  • Another page: with the help of WeUI’s nine grid component, give some common keywords, set icon picture, size

  • Create a new page under the new page and place the map of points of interest

  • Add click events to the ninth grid to jump to the map of interest points

    • The jump needs to pass the parameter, use data- parameter name, read useE.c. with our fabrication: urrentTarget. Dataset. The property name
    • – navigateTo, navigateTo, navigateTo, navigateTo The ginseng
  • The page accepts parameters, which can be obtained using parameters in onLader

  • Set the keyword to the title -setnavigationBarTitle

  • Use the Amap API – find points of interest around you

    • Page to introduce Amap, call API, pass parameters, get data
  • The returned markers can be used as anchor marker data, and be careful to save a global copy for later use

  • Stores anchor mark and current location latitude and longitude data to data

  • Write map labels, display maps, bind data (refer to home page map)

  • Add two functions:

    • Show the current point information, store it in data, and bind it to the bottom display area. Remember the binding location, which is needed for later navigation
    • Modify the current point icon: Changes the current point icon, restores other points, and saves new markers to the data-markers
  • -bindMarkerTap: parameter e with the current point information, from which to obtain the ID, again call the above show the current point information and modify the current point icon two methods

{
  "pages": [
    / / the new page
    "pages/index/index".// Secondary page
    "pages/index/around"."pages/home/home"."pages/logs/logs"],... }Copy the code
<! --index.wxml-->
<view class="page" data-weui-theme="{{theme}}">
	<view class="page__hd">
		<view class="page__desc">Search around</view>
	</view>
  <! -- Palace assembly -->
	<view class="weui-grids">
  <! -- Iterate through data to create grid components, add click event jump, set custom properties to carry parameters -->
		<a class="weui-grid" wx:for="{{around_title}}" wx:key="key" bindtap="toAround" data-keyword="{{item}}">
			<view class="weui-grid__icon">
				<image src=".. /.. /static/images/featured.png" alt></image>
			</view>
			<view class="weui-grid__label">{{item}}</view>
		</a>
	</view>
</view>
Copy the code
// index.js
const app = getApp()

Page({
  data: {
    // Create the text for the grid
    around_title: ['food'.'hotel'.'Gas station'.'hospital'.'pharmacy'.'Banks'.'the'.'Bus station'.'bathroom']},onLoad(){},// Click the event function
  toAround: (e) = > {
    // wechat jump API
    wx.navigateTo({
      // Carry parameters to the route
      url: `around? keyword=${e.currentTarget.dataset.keyword}`,})}})Copy the code
/**index.wxss**/
.weui-grid image {
  height: 30px;
  width: 30px;
}
.page__hd {
  margin-left: 20px;
}
Copy the code
<! --pages/index/around.wxml-->
<view class="container">
<! Map component, bind data, add click marker event -->
  <map class="map" name="" longitude='{{longitude}}' latitude='{{latitude}}' markers='{{markers}}' scale="14" bindmarkertap="chagenMarker"></map>
  <! -- Bottom float position display -->
  <view class="map-text">
  <! -- Bind data -->
    <text>{{info.name}}</text>
    <text>{{info.address}}</text>
    <view class="button-sp-area">
      <a class="weui-btn weui-btn_mini weui-btn_primary">button</a>
    </view>
  </view>
</view>
Copy the code
// pages/index/around.js

// Introduce amap
const {
  map
} = require('.. /.. /utils/amap-config')
// Create global marker data and store it here
let markersData = []
Page({
  /** * initial data for the page */
  data: {},/** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // bind this to
    const that = this
    // Get the search keyword
    const keyword = options.keyword
    // Modify the top title
    wx.setNavigationBarTitle({
      title: 'surrounding' + keyword,
    })
    // Call autonavi API to get interest points
    map.getPoiAround({
      // API parameters - keywords
      querykeywords: keyword,
      // called after success
      success: res= > {
        // Store fetch data
        markersData = res.markers
        // If the content is retrieved
        if (markersData.length > 0) {
          // Save data to data
          that.setData({
            markers: markersData,
            / / the latitude and longitude
            latitude: wx.getStorageSync('latitude'),
            longitude: wx.getStorageSync('longitude')})}// Call the method to modify the text, with the first data selected by default
        that.saveInfo(markersData, 0)
        // Call the method to modify the check icon, the default is the first data
        that.chagenIcon(markersData, 0)}})},// Modify the bottom text method
  // Parameters: data source, index value
  saveInfo: function (data, index) {
    // Directly modify the data in data
    this.setData({
      info: {
        name: data[index].name,
        address: data[index].address,
        id: data[index].id
      }
    })
  },
  // Modify the icon method
  // // Parameters: data source and index
  chagenIcon: function (data, index) {
    // Create an empty array to store new data
    let newMarkersData = []
    // Iterate over the data source
    for (let i = 0; i < data.length; i++) {
      / / data
      const markerItem = data[i]
      // Modify the selected data icon to restore the other ICONS to their default values
      if (i === index) {
        markerItem.iconPath = '.. /.. /static/images/marker_checked.png'
      } else {
        markerItem.iconPath = '.. /.. /static/images/marker.png'
      }
      // Store data in array
      newMarkersData.push(markerItem)
    }
    // Save the new data and modify the data
    this.setData({
      markers: newMarkersData
    })
  },
  // Click the mark point event function
  chagenMarker: function (e) {
    / / to get id
    const id = e.detail.markerId
    // Call the above two functions to pass the parameter
    this.saveInfo(markersData, id)
    this.chagenIcon(markersData, id)
  },
  /** * lifecycle function - listen for the page to complete the first rendering */
  onReady: function () {},/** * lifecycle function -- listens for page display */
  onShow: function () {},/** * life cycle function - listen for page hiding */
  onHide: function () {},/** * life cycle function - listen for page unload */
  onUnload: function () {},/** * page-related event handlers -- listen for user pull actions */
  onPullDownRefresh: function () {},/** * the handler for the pull-down event on the page */
  onReachBottom: function () {},/** * Users click on the upper right corner to share */
  onShareAppMessage: function () {}})Copy the code
/* pages/index/around.wxss */
/* /* */
.container {
  height: 100vh;
  width: 100vw;
}

/ * * / map
.map {
  width: 100%;
  height: 100%;
}

/* Bottom text */
.map-text {
  position: relative;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  /* text-align: center; * /
}

/* // Bottom text */
.map-text > text {
  display: block;
  margin: 10px 20px;
}
.map-text > text:nth-child(2) {
  font-size: 14px;
  color: # 666;
}
.map-text > .button-sp-area {
  position: absolute;
  right: 20px;
  top: 50%;
  margin-top: -16px;
}
Copy the code

Path planning

Travel on foot

Use autonavi getWalkingRoute

  • Two point coordinates

    • Starting point: Current location
    • Endpoint: other means of acquisition, search, or interest
  • At the bottom you can see the description of the walking navigation

  • Create a path planning page

  • Bind the click event to the drop-down list of the search box, click it to go to the path planning page – Bindtap

  • The jump carries parameters, which are terminal coordinates

  • The TAB menu at the top of the path planning page is modified using weui-tabbar

  • Different TAB options lead to different pages (walking, cycling, driving, bus), so you need to have four navigation pages, add custom attributes to the four tabs (the same as the page name), easy to jump to later

  • Set the TAB icon and adjust the style

  • TAB add click event, click to jump to the corresponding page, jump path should not only have a path, but also the latitude

  • Jump over to determine whether the latitude and longitude transfer, no error transmission

  • Given start and end marker data (icon, latitude and longitude)

  • Put in the map component, bind data to check whether the start and end points are loaded

  • The starting and ending lines are set with the Polyline property and bound to data

  • Call getWalkingRoute, pass starting point and ending point coordinates, and receive data

  • The polyline value of each member of the steps in the returned data is the coordinate of each point passed by the path. The coordinate of all points is joined together (into an array) to form a line

  • A polyline splits out multiple coordinates, and the reddest splits them into groups of latitude and longitude

  • Finally, pass these points to Data, and set the color and width

  • Get the navigation text information from the path interface in the returned data (stored in data)

  • You also need to save the distance and estimated time

  • Add box writing structure binding data at bottom of page

  • Add a detail button, click to expand the details. It is suggested to use dynamic height at the bottom, which is specified in data, and only need to modify the value when clicking

  • In addition, the text list can also be dynamically displayed, not displayed when there is no click details, click after loading

  • Add click events to the details button, judge whether the current state is expanded (whether the list is displayed) each time, and modify data

  • Finally, make style adjustments

// Add four pages to place four navigation pages
"pages": [
  "pages/home/home"."pages/index/index"."pages/index/around"."pages/logs/logs"."pages/route/walk"."pages/route/bike"."pages/route/bus"."pages/route/car"].Copy the code
/**app.wxss**/
/* Introduce WeUI */
@import './weui.wxss';

/* Page large container */
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
}

/* Select Tab */
.weui-tabbar__item {
  background: #3edfff;
}

/* Page large container */
.page {
  width: 100vw;
  height: 100vh;
}
Copy the code
<! --pages/home/home.wxml-->
<view class="container">
  <! -- Top search box -->
  <view class="page__bd">
    <view class="weui-search-bar {{inputShowed ? 'weui-search-bar_focusing' : ''}}" id="searchBar">
      <form class="weui-search-bar__form">
        <view class="weui-search-bar__box">
          <i class="weui-icon-search"></i>
          <input type="text" class="weui-search-bar__input" placeholder="Search" value="{{inputVal}}"
            focus="{{inputShowed}}" bindinput="inputTyping" />
          <span class="weui-icon-clear" wx:if="{{inputVal.length > 0}}" bindtap="clearInput"></span>
        </view>
        <label class="weui-search-bar__label" bindtap="showInput">
          <i class="weui-icon-search"></i>
          <span class="weui-search-bar__text">search</span>
        </label>
      </form>
      <view class="weui-search-bar__cancel-btn" bindtap="hideInput">cancel</view>
    </view>
    <view class="weui-cells searchbar-result" wx:if="{{inputVal.length > 0}}">
      <! -- Iterate over data to create search prompt results, add click events, Tina's custom properties to pass coordinates -->
      <view class="weui-cell weui-cell_active weui-cell_access" wx:for="{{tips}}" wx:key='id' bindtap="toRoute"
        data-location="{{item.location}}">
        <view class="weui-cell__bd weui-cell_primary">
          <view>{{item.name}}</view>
        </view>
      </view>
    </view>
  </view>
  <! -- Map component, set latitude and longitude, marker information -->
  <map class="map" name="" longitude='{{longitude}}' latitude='{{latitude}}' markers='{{markers}}' scale="14"></map>
  <! -- Bottom float position display -->
  <view class="map-text">
    <text>{{markers[0].name}}</text>
    <text>{{markers[0].desc}}</text>
    <view class="button-sp-area">
      <a class="weui-btn weui-btn_mini weui-btn_primary">navigation</a>
    </view>
  </view>
</view>
Copy the code
// pages/home/home.js

const amap = require('.. /.. /utils/amap-config')
Page({

  /** * initial data for the page */
  data: {
    inputShowed: false.inputVal: ""
  },
  // Click the TV search box time event function
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  // Cancel the button click event function
  hideInput: function () {
    this.setData({
      inputVal: "".inputShowed: false
    });
  },
  // Clear the button click event function
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  // Text box input event
  inputTyping: function (e) {
    // Store input
    this.setData({
      inputVal: e.detail.value
    });
    // Call the method to get prompt data
    this.getTips(e.detail.value)
  },
  // Get input prompt data
  getTips: function (keywords) {
    // Store this pointer
    const that = this
    // Call the Gaud method to get an input reminder
    amap.map.getInputtips({
      // Enter the content
      keywords,
      // Location information
      location: that.data.longitude + ', ' + that.data.latitude,
      // called after success
      success: (res) = > {
        // If the data is successfully obtained, the data is stored
        if (res && res.tips) that.setData({
          tips: res.tips
        })
        console.log(that.data.tips); }})},/** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // Store this pointer
    const that = this
    // Read local location information and store it in data
    that.setData({
      longitude: wx.getStorageSync('longitude'),
      latitude: wx.getStorageSync('latitude')})// Call gaode inverse address resolution to obtain the location information of coordinates
    amap.map.getRegeo({
      // Successful call
      success: res= > {
        console.log(res);
        // Use data as markup information
        // Set the tag to use the image
        res[0].iconPath = '/static/images/location.png'
        // Store markup data locally
        that.setData({
          markers: res
        })
      },
      // Failure Displays failure information
      fail: err= > {
        console.log(err)
      }
    })
  },
  // Search results prompt list of click events
  toRoute: function (e) {
    // Jump to the page with parameters
    wx.navigateTo({
      url: `.. /route/walk? location=${e.currentTarget.dataset.location}`,})}})Copy the code
<! --pages/route/walk.wxml-->
<view class="page">
  <! Top Tab navigation bar -->
  <view class="page__bd">
    <view class="weui-tab">
      <view class="weui-tab__panel">
      </view>
      <view class="weui-tabbar">
        <! -- Set custom properties, pass parameters when jumping, modify ICONS and names -->
        <view class="weui-tabbar__item weui-bar__item_on" bindtap="toRoute" data-route='walk'>
          <view style="display: inline-block; position: relative;">
            <image src=".. /.. /static/images/walk-active.png" alt class="weui-tabbar__icon"></image>
          </view>
          <view class="weui-tabbar__label">walking</view>
        </view>
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='car'>
          <image src=".. /.. /static/images/car.png" alt class="weui-tabbar__icon"></image>
          <view class="weui-tabbar__label">driving</view>
        </view>
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='bus'>
          <view style="display: inline-block; position: relative;">
            <image src=".. /.. /static/images/bus.png" alt class="weui-tabbar__icon"></image>
          </view>
          <view class="weui-tabbar__label">The bus</view>
        </view>
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='bike'>
          <image src=".. /.. /static/images/bike.png" alt class="weui-tabbar__icon"></image>
          <view class="weui-tabbar__label">cycling</view>
        </view>
      </view>
    </view>
  </view>
  <! -- Map component, bind data, Polyline -- used to compose path render -->
  <map class="map" name="" longitude='{{markers[0].longitude}}' latitude='{{markers[0].latitude}}' markers='{{markers}}'
    scale="14" polyline='{{polyline}}'></map>
  <! -- Bottom details, bind dynamic height -->
  <view class='info' style="max-height: {{listHeight}};">
    <! -- Time and distance, bind data -->
    <text class='info-text'>Distance}} km, expected to take {{duration}} minutes</text>
    <! -- Detail list, iterate and bind data -->
    <view class='infoList' wx:if="{{listShow}}">
      <text class='infoList-item' wx:for="{{steps}}" wx:key='steps'>{{item.instruction}}</text>
    </view>
    <! -- Button, bind data, add click event -->
    <button class="mini-btn" size="mini" bindtap="clickBtn">{{buttonText}}</button>
  </view>
</view>
Copy the code
// pages/route/walk.js
// Introduce amap
const {
  map
} = require('.. /.. /utils/amap-config')

Page({

  /** * initial data for the page */
  data: {
    // Whether the details are displayed
    listShow: false.// Detail height
    listHeight: '70px'.// Button text
    buttonText: 'a'
  },

  /** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // Check whether the destination coordinates are passed when the jump is over, if not, return directly
    if (options.location === ' ') {
      return console.log('Latitude and longitude error')}/ / bind this
    const that = this
    // Save data
    that.setData({
        // End coordinates
        location: options.location,
        // Start longitude and latitude
        longitude: wx.getStorageSync('longitude'),
        latitude: wx.getStorageSync('latitude'),
        // Two markers - the starting point and the ending point are set separately
        markers: [{
          longitude: wx.getStorageSync('longitude'),
          latitude: wx.getStorageSync('latitude'),
          iconPath: '.. /.. /static/images/nav_s.png'
        }, {
          longitude: options.location.split(', ') [0].latitude: options.location.split(', ') [1].iconPath: '.. /.. /static/images/nav_e.png'}}),// Call the Amap API to get the path
      map.getWalkingRoute({
        // Parameter - starting coordinates
        origin: that.data.longitude + ', ' + that.data.latitude,
        // Parameter - endpoint coordinates
        destination: that.data.location,
        // Successful call
        success: data= > {
          // Create an empty array to store path coordinates
          let points = []
          // Determine whether data is requested
          if (data.paths && data.paths[0] && data.paths[0].steps) {
            // Get the path
            const steps = data.paths[0].steps
            // Traverses the path
            for (let i = 0; i < steps.length; i++) {
              // Get the coordinates of the path
              const array = steps[i].polyline.split('; ')
              // The coordinates are iterated
              for (let j = 0; j < array.length; j++) {
                // Add each pair of latitude and longitude stored as an object to the array
                points.push({
                  longitude: array[j].split(', ') [0].latitude: array[j].split(', ') [1],})}}}// data Saves data
          that.setData({
            // Parameters needed by the map component
            polyline: [{
              // Set of path coordinates
              points,
              / / color
              color: '#4da2fd'./ / line width
              width: 5}]./ / distance
            distance: (data.paths[0].distance / 1000).toFixed(2),
            / / time
            duration: (data.paths[0].duration / 60).toFixed(1),
            // Save a copy of the path
            steps: data.paths[0].steps
          })
        },
      })
  },
  // Click the top Tab to jump to the page function
  toRoute: function (e) {
    // Jump to the page. Passing parameters
    wx.navigateTo({
      url: `${e.currentTarget.dataset.route}? location=The ${this.data.location}`,}}),// Click to expand and collapse the event functions
  clickBtn: function () {
    / / bind this
    const that = this
    // Modify the data according to the current state
    if(! that.data.listShow) { that.setData({listShow: true.listHeight: '80vh'.buttonText: 'put'})}else {
      that.setData({
        listShow: false.listHeight: '70px'.buttonText: 'a'}}}})Copy the code
/* pages/route/walk.wxss */
/* Top Tab */
.page__bd {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1;
}

/ * * / map
.map {
  width: 100%;
  height: 100%;
}

/* Bottom details */
.info {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 10px;
  background-color: #fff;
  z-index: 1;
  overflow: auto;
}

.info .info-text {
  height: 50px;
  line-height: 50px;
}

.info button {
  position: absolute;
  top: 19px;
  right: 30px;
  background-color: #009dfe;
  color: #fff;
}

.info .infoList-item {
  display: block;
  padding: 5px 0;
  color: # 666;
  font-size: 14px;
}
Copy the code

The following is a common structure for the other three pages, but has not yet written the line fill content, which is the same as walking navigation

Page({

  /** * initial data for the page */
  data: {},/** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // Check whether the destination coordinates are passed, and return an error if not
    if (options.location === ' ') {
      return console.log('Latitude and longitude error')}/ / bind this
    const that = this
    // Save data
    that.setData({
      // End coordinates
      location: options.location,
      // Start longitude and latitude
      longitude: wx.getStorageSync('longitude'),
      latitude: wx.getStorageSync('latitude')})},// Click Tab to jump to the event
  toRoute: function (e) {
    wx.navigateTo({
      // Pass parameters
      url: `${e.currentTarget.dataset.route}? location=The ${this.data.location}`,})}})Copy the code
<view class="page">
<! -- Top Tab -->
  <view class="page__bd" style="height: 100%;">
    <view class="weui-tab">
      <view class="weui-tab__panel">
      </view>
      <view class="weui-tabbar">
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='walk'>
          <view style="display: inline-block; position: relative;">
            <image src=".. /.. /static/images/walk.png" alt class="weui-tabbar__icon"></image>
          </view>
          <view class="weui-tabbar__label">walking</view>
        </view>
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='car'>
          <image src=".. /.. /static/images/car.png" alt class="weui-tabbar__icon"></image>
          <view class="weui-tabbar__label">driving</view>
        </view>
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='bus'>
          <view style="display: inline-block; position: relative;">
            <image src=".. /.. /static/images/bus.png" alt class="weui-tabbar__icon"></image>
          </view>
          <view class="weui-tabbar__label">The bus</view>
        </view>
        <view class="weui-tabbar__item weui-bar__item_on" bindtap="toRoute" data-route='bike'>
          <image src=".. /.. /static/images/bike-active.png" alt class="weui-tabbar__icon"></image>
          <view class="weui-tabbar__label">cycling</view>
        </view>
      </view>
    </view>
  </view>
</view>
Copy the code

Cycling and driving navigation

  • The logic is similar to walking navigation, but the API is different and can be modified directly on walking
    • Ride navigation: getRidingRoute
    • Driving directions: getDrivingRoute

Here, copy the walking code directly and modify it

<! --pages/route/bike.wxml-->
<view class="page">
  <! Top Tab navigation bar -->
  <view class="page__bd">
    <view class="weui-tab">
      <view class="weui-tab__panel">
      </view>
      <view class="weui-tabbar">
        <! -- Set custom properties, pass parameters when jumping, modify ICONS and names -->
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='walk'>
          <view style="display: inline-block; position: relative;">
            <image src=".. /.. /static/images/walk.png" alt class="weui-tabbar__icon"></image>
          </view>
          <view class="weui-tabbar__label">walking</view>
        </view>
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='car'>
          <image src=".. /.. /static/images/car.png" alt class="weui-tabbar__icon"></image>
          <view class="weui-tabbar__label">driving</view>
        </view>
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='bus'>
          <view style="display: inline-block; position: relative;">
            <image src=".. /.. /static/images/bus.png" alt class="weui-tabbar__icon"></image>
          </view>
          <view class="weui-tabbar__label">The bus</view>
        </view>
        <view class="weui-tabbar__item weui-bar__item_on" bindtap="toRoute" data-route='bike'>
          <image src=".. /.. /static/images/bike-active.png" alt class="weui-tabbar__icon"></image>
          <view class="weui-tabbar__label">cycling</view>
        </view>
      </view>
    </view>
  </view>
  <! -- Map component, bind data, Polyline -- used to compose path render -->
  <map class="map" name="" longitude='{{markers[0].longitude}}' latitude='{{markers[0].latitude}}' markers='{{markers}}'
    scale="14" polyline='{{polyline}}'></map>
  <! -- Bottom details, bind dynamic height -->
  <view class='info' style="max-height: {{listHeight}};">
    <! -- Time and distance, bind data -->
    <text class='info-text'>Distance}} km, expected to take {{duration}} minutes</text>
    <! -- Detail list, iterate and bind data -->
    <view class='infoList' wx:if="{{listShow}}">
      <text class='infoList-item' wx:for="{{steps}}" wx:key='steps'>{{item.instruction}}</text>
    </view>
    <! -- Button, bind data, add click event -->
    <button class="mini-btn" size="mini" bindtap="clickBtn">{{buttonText}}</button>
  </view>
</view>
Copy the code
// pages/route/bike.js
// pages/route/car.js
// Introduce amap
const {
  map
} = require('.. /.. /utils/amap-config')

Page({

  /** * initial data for the page */
  data: {
    // Whether the details are displayed
    listShow: false.// Detail height
    listHeight: '70px'.// Button text
    buttonText: 'a'
  },

  /** * lifecycle function -- listens for page loading */
  onLoad: function (options) {
    // Check whether the destination coordinates are passed when the jump is over, if not, return directly
    if (options.location === ' ') {
      return console.log('Latitude and longitude error')}/ / bind this
    const that = this
    // Save data
    that.setData({
        // End coordinates
        location: options.location,
        // Start longitude and latitude
        longitude: wx.getStorageSync('longitude'),
        latitude: wx.getStorageSync('latitude'),
        // Two markers - the starting point and the ending point are set separately
        markers: [{
          longitude: wx.getStorageSync('longitude'),
          latitude: wx.getStorageSync('latitude'),
          iconPath: '.. /.. /static/images/nav_s.png'
        }, {
          longitude: options.location.split(', ') [0].latitude: options.location.split(', ') [1].iconPath: '.. /.. /static/images/nav_e.png'}}),console.log('ride');
      // Call the Amap API to obtain the path!!!!!!!!!!!!!!!!!!!!!! Just modify the call interface, and drive, walk, and ride pass parameters and return results with the same structure
      map.getRidingRoute({
        // Parameter - starting coordinates
        origin: that.data.longitude + ', ' + that.data.latitude,
        // Parameter - endpoint coordinates
        destination: that.data.location,
        // Successful call
        success: data= > {
          // Create an empty array to store path coordinates
          let points = []
          // Determine whether data is requested
          if (data.paths && data.paths[0] && data.paths[0].steps) {
            // Get the path
            const steps = data.paths[0].steps
            // Traverses the path
            for (let i = 0; i < steps.length; i++) {
              // Get the coordinates of the path
              const array = steps[i].polyline.split('; ')
              // The coordinates are iterated
              for (let j = 0; j < array.length; j++) {
                // Add each pair of latitude and longitude stored as an object to the array
                points.push({
                  longitude: array[j].split(', ') [0].latitude: array[j].split(', ') [1],})}}}// data Saves data
          that.setData({
            // Parameters needed by the map component
            polyline: [{
              // Set of path coordinates
              points,
              / / color
              color: '#4da2fd'./ / line width
              width: 5}]./ / distance
            distance: (data.paths[0].distance / 1000).toFixed(2),
            / / time
            duration: (data.paths[0].duration / 60).toFixed(1),
            // Save a copy of the path
            steps: data.paths[0].steps
          })
        },
        fail: info= > {
          console.log('failure'); }})},// Click the top Tab to jump to the page function
  toRoute: function (e) {
    // Jump to the page. Passing parameters
    wx.navigateTo({
      url: `${e.currentTarget.dataset.route}? location=The ${this.data.location}`,}}),// Click to expand and collapse the event functions
  clickBtn: function () {
    / / bind this
    const that = this
    // Modify the data according to the current state
    if(! that.data.listShow) { that.setData({listShow: true.listHeight: '80vh'.buttonText: 'put'})}else {
      that.setData({
        listShow: false.listHeight: '70px'.buttonText: 'a'}}}})Copy the code
/* pages/route/bike.wxss */
/* Top Tab */
.page__bd {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1;
}

/ * * / map
.map {
  width: 100%;
  height: 100%;
}

/* Bottom details */
.info {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 10px;
  background-color: #fff;
  z-index: 1;
  overflow: auto;
}

.info .info-text {
  height: 50px;
  line-height: 50px;
}

.info button {
  position: absolute;
  top: 19px;
  right: 30px;
  background-color: #009dfe;
  color: #fff;
}

.info .infoList-item {
  display: block;
  padding: 5px 0;
  color: # 666;
  font-size: 14px;
}
Copy the code

Driving is not posted here, and only one interface has been modified

Note: there may be some problems with the riding interface, still trying

Bus travel

Interface: getTransitRoute

Unlike the interface called earlier, the bus needs to pass an extra city parameter and transfer policy

Multiple transfer strategies are provided – this value needs to be passed to the interface:

  • 0: the fastest mode

  • 1: The most economical model

  • 2: Minimum transfer mode

  • 3: Minimum walking mode

  • 5: No subway mode (note)

  • Provides selection of city functions

  • Add a transfer policy in data (Chinese, for display), can be written first

  • Page to add a button to modify transfer policy, set style

  • Use the apI-Showactionsheet of wechat to select the transfer strategy, modify the scheme in data, and pay attention not to take the subway

  • Enter the page to obtain the starting and ending coordinates and two-point marks

  • Load directly call the bus interface, you can use the most convenient -0, separate encapsulation of this function

  • Transfer parameters: 7-point coordinate, terminal coordinate, travel strategy, city

  • Cities can be written down globally first

  • The required data is processed and saved to data

  • The page traverses and presents the data

  • Add logic to travel policy change, call API again to get path plan, pass parameters

<! --pages/route/bus.wxml-->
<view class="page">
  <! Top Tab navigation bar -->
  <view class="page__bd">
    <view class="weui-tab">
      <view class="weui-tab__panel">
      </view>
      <view class="weui-tabbar">
        <! -- Set custom properties, pass parameters when jumping, modify ICONS and names -->
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='walk'>
          <view style="display: inline-block; position: relative;">
            <image src=".. /.. /static/images/walk.png" alt class="weui-tabbar__icon"></image>
          </view>
          <view class="weui-tabbar__label">walking</view>
        </view>
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='car'>
          <image src=".. /.. /static/images/car.png" alt class="weui-tabbar__icon"></image>
          <view class="weui-tabbar__label">driving</view>
        </view>
        <view class="weui-tabbar__item weui-bar__item_on" bindtap="toRoute" data-route='bus'>
          <view style="display: inline-block; position: relative;">
            <image src=".. /.. /static/images/bus-active.png" alt class="weui-tabbar__icon"></image>
          </view>
          <view class="weui-tabbar__label">The bus</view>
        </view>
        <view class="weui-tabbar__item" bindtap="toRoute" data-route='bike'>
          <image src=".. /.. /static/images/bike.png" alt class="weui-tabbar__icon"></image>
          <view class="weui-tabbar__label">cycling</view>
        </view>
      </view>
    </view>
  </view>
  <! -- Travel Strategy button -->
  <view class="button-sp-area cell">
    <a class="weui-btn_cell weui-btn_cell-primary" bindtap="chagenStrategy">Travel Strategy ({{strategy}})</a>
  </view>
  <! -- Travel plan List display -->
  <view class="weui-panel weui-panel_access">
    <view class="weui-panel__bd" wx:for="{{nameList}}" wx:key='nameList'>
      <view class="weui-media-box weui-media-box_text">
        <text>{{item}}</text>
        <view class="weui-media-box__desc">Other things to show</view>
      </view>
    </view>
  </view>
</view>
Copy the code
// pages/route/bus.jsconst { map } = require('.. /.. /utils/amap-config') Page({/** * initial data for the page */
  data: {
    strategy: 'Most convenient'
  },

  /** * lifecycle function -- listens for page loading */OnLoad: function (options) {return if (options.location ===' ') {
      return console.log('Latitude and longitude error'} // bind this const that = this // save data that.setData{// End coordinates longitude: options.location, // start longitude longitude: wx.getStorageSync('longitude'),
      latitude: wx.getStorageSync('latitude'}) // Call method initialization to get data that.getTransitRoute(0}, // click Tab to jump to the event toRoute: function (e) {wxnavigateToTo pass an argument ({/ / url: ` ${urrentTarget of e.c. with our fabrication:. The dataset. The route}? location=${this.data.location} ',})}, // Function () {const that = this const itemList = [const itemList = ['Quickest'.'most economical'.'Less interchange'.'Walk less'.'No subway'] // Call the interface to pop up selector wx.showActionSheet({// data source itemList, // select successful callsuccess(res) {// Get the selection ordinal, note here because the Autonavi API parameter does not exist4Is one if yes4Const strategyNum = res.tapIndex ===4 ? 5: res.tapindex // Modify the text that.setData({strategy: itemList[res.tapIndex]}) // Call the method to retrieve the travel plan that.getTransitRoute(strategyNum)}})}, // Travel scheme acquisition method // parameter: autonavi API needs to use the parameter getTransitRoute: Function (type) {// bind this const that = this // call autonavi API map.getTransitRoute{// parameter - current position origin: wx.getStorageSync('longitude') + ', ' + wx.getStorageSync('latitude'Destination: that.data.location, // strategy: type, // start city, // start city, // start city:'Beijing'// Success: Data => {if (data && data.transits) {const transits = data.transits Const nameList = [] // loop through all options for (let I =0; i < transits.length; i++) {const segments = transits[i].segments// To hold the path name corresponding to the scheme const nameArr =[]For (let j =0; j < segments.length; J++) {// determine whether path information exists if (segments)[j].bus && segments[j].bus.buslines && segments[j].bus.buslines[0] && segments[j].bus.buslines[0].name) {// obtain path let name = segments[j].bus.buslines[0].nameIf (j! = =0) {name = '-->' + name} // Save path nameArr.push(name)}} // Join all paths in a list to form a nameList.push(nameArr.join("))} // Save all the final schema information to data that.setData({
            nameList
          })
        }
      }
    })
  }
})
Copy the code
/* pages/route/bus.wxss */
.page__bd {
  width: 100%;
  margin-bottom: 10px;
}

.weui-btn_cell {
  background: #ccc;
}
Copy the code

Total surrender line select city

Possible knowledge points

  • Rolling diagram:<scroll-view>
  • GetSystemInfo: wx.getSystemInfo – wechat version number, language, platform information, screen size…
  • Events: touchstart – finger touch, touchmove – finger touch after move, touchend – finger touchend
  • GetCurrentPages – Get the current routing station, can get the last page, so that you can modify data across pages

It’s a little bit complicated here, so I’m not going to write it

Publish applets

  1. Set the applet category
  2. Submit code
    1. Wechat developer tools
      1. Bind real applets APPID (do not bind public ID)
      2. Upload code (cannot upload without binding)
    2. Applet background
      1. Administration – Version Management – Commit code
  3. Binding a Legitimate Domain name
    1. Development – Development Management – Server domain name – Request Legitimate domain name (HTTPS)