Vue introduces Gaode map: realize map display and interaction

Vue introduces Gaode map: realize map display and interaction

This article will introduce how to introduce Gaode map into the Vue project, and how to realize the display and interaction functions of the map. We will start by installing dependencies, then configure the key and related plug-ins of Gaode map, and finally demonstrate how to use the map component in Vue components and realize basic interactive functions. Through the guidance of this article, you will be able to easily integrate Gaode map in the Vue project to realize the display and interaction of the map.

1 Introduction

1.1 Research Background

Map presentation and map interaction play an important role in many web applications. With the popularity of mobile devices and the development of location-based services, users have higher and higher demands on maps. Introducing AutoNavi Maps into the Vue project can provide users with an interactive map experience and add more functionality and value to the application.

AutoNavi Maps is a leading provider of digital map content, navigation and location service solutions in China. It provides a wealth of map data and features, including geocoding, reverse geocoding, route planning, place search, and more. By introducing Gaode Map into the Vue project, we can realize the display and interaction of the map, and add some custom functions to meet the needs of users.

Vue is a modern JavaScript framework for building user interfaces. Its componentized development mode and responsive data binding make it easier and more flexible to introduce AutoNavi into Vue projects. By integrating Gaode Map into the Vue application, we can easily manage the map component and interact with other components. This provides us with the convenience and flexibility to develop complex map applications.

Therefore, the combination of Vue and Gaode map can provide users with a good map display and interactive experience, and add more interesting and practical functions to the application. This is of great significance for various application scenarios such as map navigation, place search, and location services. By researching and practicing the method and technology of Vue's introduction of Gaode Map, we can better master this technology and apply it to actual projects to bring better experience and value to users.

1.2 Research purpose and significance

This research aims to explore the methods and technologies of introducing AutoNavi into the Vue project to realize map display and interaction, as well as its purpose and significance.

  1. Research on map display and interaction technology: By studying the methods and technologies of introducing AutoNavi maps into the Vue project, we can gain a deep understanding of the technical implementation principles and related concepts of map display and interaction. This helps us gain a more comprehensive understanding of GIS and LBS technologies, and enhances our technical capabilities in the field of map development.

  2. Provide user-friendly map experience: Map display and interaction is one of the important functions of many web applications, which can provide users with intuitive and convenient map browsing and interactive experience. By introducing AutoNavi into the Vue project, we can customize the map function according to user needs and provide a more friendly and personalized map experience, thereby increasing the user stickiness and competitiveness of the application.

  3. Rich application functions and values: AutoNavi Maps provides a wealth of map data and functions, including geocoding, reverse geocoding, route planning, location search, etc. By introducing AutoNavi into the Vue project, we can integrate these functions into the application, provide users with more practical and convenient map-related functions, and enrich the functionality and value of the application.

  4. Technical skills improvement and innovation: Studying the methods and technologies of Vue's introduction of AutoNavi maps can improve our technical capabilities in the field of Vue framework and map development, and broaden our technical horizons. At the same time, we can discover and solve some technical challenges related to map display and interaction in practice, thereby promoting technological innovation and development.

  5. Development and application of practical projects: By studying the methods and technologies of Vue's introduction of AutoNavi maps, we can master the complete process of map display and interaction in Vue projects, and provide guidance and support for the development of actual projects. This has important practical and application value for developing applications with map functions, such as map navigation, place search, location service, etc.

Researching the method and technology of Vue's introduction of Gaode Map is of great significance and value to promote the development of map display and interaction. By integrating AutoNavi Maps into the Vue project, we can expand the functionality and user experience of the app, and provide users with better and more convenient map services. At the same time, for developers, mastering these technologies will also enhance their competitiveness and innovation in the field of map development.

2 Vue framework overview

2.1 Basic principles of Vue framework

The basic principle of the Vue framework is based on the componentized development model. In Vue, pages are split into small, reusable components, which can be nested to form complex interfaces. Vue realizes the separation of data and views through the encapsulation and management of components, so that developers can pay more attention to data processing and logic implementation.

The core principles of Vue include the following aspects:

  1. Responsive data: Vue uses the data hijacking and observation mechanism to automatically update the view when the data changes by detecting data changes. When we modify the data of a Vue instance, Vue internally intercepts the modification of the data through the setter method, and then notifies the relevant dependencies to update.

  2. Virtual DOM: Vue uses virtual DOM as the middle layer. By comparing the difference between the old and new virtual DOM, it minimizes the number of operations on the real DOM and improves performance. When the data changes, Vue will immediately build a new virtual DOM tree, compare it with the old virtual DOM tree, find out the difference, and then only update the parts that need to be updated.

  3. Componentized Architecture: Components in Vue can be thought of as an independent, reusable module, each with its own data and views. Components can be nested to form complex interfaces, and data and messages can also be passed through communication between components. Vue's componentization allows developers to organize and manage code more efficiently.

  4. Life cycle: Vue components have a complete set of life cycle hooks, each stage has a corresponding callback function, and developers can perform some operations at specific times. For example, before the component is created, data can be initialized in the beforeCreate hook; before the component is destroyed, the cleanup operation can be performed in the beforeDestroy hook.

The basic principle of the Vue framework is to implement data-driven view updates through mechanisms such as responsive data, virtual DOM, component architecture, and life cycle, thereby improving development efficiency and performance.

2.2 Application of Vue framework in web application

The Vue framework is widely used in web applications, the following are some common application scenarios:

  1. Single Page Application (SPA): The Vue framework is great for developing Single Page Applications. By using Vue's routing function, you can achieve non-refresh switching between pages and display corresponding components according to different routes. This approach provides a smoother user experience and higher performance.

  2. Dynamic data display: Vue's reactive data binding makes it very easy to display data dynamically in web applications. Developers can bind data to Vue instances, so that data changes can be automatically reflected on the user interface to achieve instant updates and displays.

  3. Form processing: Vue provides powerful form processing functions. Developers can use Vue's form directives and form components to easily create forms and implement functions such as two-way binding of form data, form validation, and form submission. This simplifies the process of form handling and improves the user experience.

  4. Component-based development: Vue's component-based development model makes it easier to build complex interfaces in web applications. Developers can divide a page into multiple small, independent components, each responsible for its own functionality. This mode improves the maintainability of the code, and also makes it easier for multiple people to collaborate on development.

  5. Plug-in extension: The Vue framework has a rich plug-in ecosystem, and developers can choose the right plug-in according to their own needs to extend the functions and capabilities of Vue. These plug-ins can be used to integrate third-party libraries, enhance development experience, optimize performance, etc., making Web applications more powerful and flexible.

The Vue framework can realize multiple functions such as single-page application, dynamic data display, form processing, and component development in web applications. It provides a simple, flexible, and efficient development method, enabling developers to build excellent user interfaces and feature-rich Web applications.

3 Introduction to AutoNavi Maps

3.1 API interface of Gaode map

AutoNavi Maps provides a wealth of API interfaces for developers to use to build various map applications and services. The following are some main API interfaces of Gaode Map:

  1. JavaScript API:

    • Map: used to display the Gaode map on the webpage, and provide interactive functions such as labeling, zooming, panning, etc.
    • Positioning: Realize functions such as obtaining user location, geocoding, and reverse geocoding.
    • Services: including static maps, IP positioning, weather query and other service interfaces.
  2. Web service API:

    • Geocoding: Convert addresses to geographic coordinates or convert geographic coordinates to detailed addresses.
    • Inverse Geocoding: Convert geographic coordinates to detailed addresses.
    • Route planning: Supports route planning services such as public transportation, driving, cycling, and walking.
    • Administrative division query: query administrative division boundaries, administrative area information, etc.
    • Search POI: Search for points of interest, businesses, addresses and other information based on keywords.
  3. Mobile SDK:

    • Positioning SDK: Obtain device location information.
    • Navigation SDK: Provides real-time route planning and navigation functions.
    • Map SDK: display maps, annotations and other functions in mobile applications.
  4. LBS cloud service:

    • Track deviation correction: perform deviation correction processing on the collected track data.
    • Trajectory query: query the trajectory data within a specific time period.
    • Silent track reporting: Realize the collection and storage of user behavior tracks.
  5. other service:

    • Static Map API: Generate static map images.
    • Photogrammetry: Provides measurement and positioning functions for geographic data.

The above are only some of the main API interfaces provided by AutoNavi Maps. Developers can choose appropriate API interfaces for development according to specific needs. Through these API interfaces, developers can implement map display, geocoding, route planning, POI search, location positioning and other functions to meet the needs of different map applications. Please note that for specific interface parameters and usage methods, please refer to the official documentation and developer guide of Amap.

3.2 Application Scenarios of AutoNavi Maps in Web Applications

Amap has a wide range of application scenarios in web applications. Here are some common application scenarios:

  1. Map display and navigation: Amap can be used to display maps in web applications, allowing users to find, browse and navigate to specific locations. This can include features such as custom markers, route displays, real-time traffic information, etc., to help users better understand location and navigation directions.

  2. Geographic location service: the API of Gaode Map can be used by web applications to obtain the user's current location, or perform geocoding and reverse geocoding based on the address provided by the user to obtain accurate latitude and longitude or address information.

  3. Route planning and navigation: The route planning API of AutoNavi Maps can help users plan the best route and navigation solutions in web applications, including driving, walking, cycling and public transportation. This can be used to implement traffic guidance, travel navigation and other functions to provide a more convenient travel experience.

  4. Search for points of interest (POI): AutoNavi Maps provides an API interface for POI search, which can search for specific points of interest in web applications based on keywords, such as restaurants, hotels, shopping malls, etc., and provide relevant information and positioning services. This makes it easier for users to find nearby service facilities that meet their needs.

  5. Visualization of geographic data: Gaode map can be used to visualize geographic data in web applications, such as heat maps, point aggregation, regional boundaries, etc. This can be used to analyze and display the distribution, trend and relationship of geographic data, providing users with more intuitive data presentation and analysis functions.

  6. Travel and traffic services: The real-time traffic information and public transportation navigation functions of Gaode map can be used by web applications to provide real-time traffic conditions, driving routes and travel suggestions. This is very helpful for users who need to understand traffic conditions and plan their trips.

AutoNavi maps can be used in many aspects such as map display, geographic location service, route planning, POI search, travel navigation, and geographic data visualization in web applications. It provides rich map data and functions, and can provide users with accurate, convenient and practical map services.

4 Introducing AutoNavi Maps into Vue

4.1 Create a Vue project

To create a Vue project, you need to follow these steps:

  1. Install Node.js and npm: The Vue project needs to run in a Node.js environment, so you first need to install Node.js. You can download the latest version of Node.js from Node.js official website ( https://nodejs.org ) and install it on your computer.

  2. Install Vue CLI: Vue CLI is a scaffolding tool for creating and managing Vue projects. Once Node.js is installed, you can install Vue CLI from the command line with the following command:

npm install -g @vue/cli
  1. Create a Vue project: After installing the Vue CLI, create a new Vue project with the following command:
vue create my-project

Among them, my-projectis your project name, you can name it yourself according to your needs.

During the process of creating a project, Vue CLI will ask you for some setting options, such as selecting a project preset (default or manually selected), selecting features, installing dependencies, etc. You can choose according to your needs.

  1. Enter the project directory: After the project is successfully created, use the following command to enter the project directory:
cd my-project

where my-projectis the name of the project you created in the previous step.

  1. Start the project: After entering the project directory, use the following command to start the Vue project:
npm run serve

This starts a local development server and opens your Vue project in the browser. You can preview and test your project by visiting the specified URL.

So far, you have successfully created a Vue project. You can edit and develop your Vue application in the project directory, and customize configuration and add Vue components as needed. Please refer to the Vue documentation ( https://vuejs.org ) and the Vue CLI documentation ( https://cli.vuejs.org ) for an in-depth look at how Vue is developed and configured.

4.2 Install the Gaode map plug-in

To use the Gaode map plugin in a Vue project, you can follow the steps below to install it:

  1. At the root of your Vue project, open a terminal or command line tool.

  2. Use npm to install the vue-amap plugin, which can be installed with the following command:

npm install vue-amap
  1. Once installed, open the file in your Vue project main.js(usually located srcin the directory).

  2. main.jsAdd the following code to the file to import the vue-amapplugin and use it:

import VueAMap from 'vue-amap';

Vue.use(VueAMap);

// 初始化 vue-amap 插件
VueAMap.initAMapApiLoader({
    
    
  // 高德地图的 key
  key: '你的高德地图 key',
  // 插件集合
  plugin: ['AMap.Geolocation', 'AMap.Marker']
});

In the above code, replace it 你的高德地图 keywith your own Amap developer key. If you have not obtained the key, you need to go to the AutoNavi open platform (https://lbs.amap.com) to register and apply.

  1. After the installation is complete, you can use the Gaode map plugin in the Vue project. In the components that need to use Gaode map, you can call the API of Gaode map in the following way:
<template>
  <div>
    <amap-map :zoom="13" :center="center">
      <amap-marker :position="position"></amap-marker>
    </amap-map>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      center: [116.397428, 39.90923],
      position: [116.397428, 39.90923]
    };
  }
};
</script>

The above code is a simple example showing how to use the map and marker functions of Amap in Vue components. According to your needs, you can further call other APIs of Gaode Map to realize more functions.

Please note that before using the Gaode map plug-in, make sure you have correctly applied for and obtained the Gaode map developer key. In addition, according to specific needs, you can configure and use it according to the documentation of the Gaode map plugin ( https://elemefe.github.io/vue-amap/ ).

4.3 Integrate Gaode map in Vue project

To integrate Gaode map in Vue project, you can follow the steps below:

  1. First of all, you need to register an account on the Gaode open platform and create an application. Obtain a web-side API Key under the application. This API Key will be used to call map-related functions in your Vue project. Please keep your API Key safe to avoid disclosure.

  2. Install the library in your Vue project vue-amap. The library can be installed with the following command:

npm install vue-amap --save
  1. In your Vue project entry file (usually main.js), import and configure vue-amap:
import VueAMap from 'vue-amap';
Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
    
    
  key: '您的 API Key',
  plugin: ['AMap.Geolocation']
});
  1. In the components that need to use the map, use <a-map>the label to render the map. For example:
<template>
  <div>
    <h1>我的地图应用</h1>
    <a-map :zoom="13">
      <a-marker :position="markerPosition"></a-marker>
    </a-map>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      markerPosition: [116.397428, 39.90923]
    };
  }
};
</script>

In this example, we place a marker on the map and specify the position of the marker as [116.397428, 39.90923].

  1. Run your Vue project, you will be able to see the page integrated with Gaode map.

This is a simple example, you can further extend and customize the map functionality according to your project needs. You can refer to vue-amapthe documentation of the library and the API documentation of Gaode Maps to learn more about functions and usage methods.

4.4 Display the map

To display a map in a Vue project, you can use the Vue-amap plugin to achieve it. Here's a simple example showing a map:

  1. In your Vue component, first import vue-amap and register it as a Vue plugin.
<template>
  <div id="map-container"></div>
</template>

<script>
import VueAMap from 'vue-amap';

export default {
      
      
  mounted() {
      
      
    Vue.use(VueAMap);
    this.initMap();
  },
  methods: {
      
      
    initMap() {
      
      
      // 初始化 vue-amap 插件
      this.$amap.initAMapApiLoader({
      
      
        key: '你的高德地图 key', // 你的高德地图 key
        plugin: ['AMap.Geocoder'] // 需要使用的高德地图插件
      });

      // 创建地图实例
      const map = new this.$amap.Map('map-container', {
      
      
        zoom: 13, // 缩放级别
        center: [116.397428, 39.90923] // 地图中心点坐标
      });

      // 添加标记点
      new this.$amap.Marker({
      
      
        position: [116.397428, 39.90923], // 标记点坐标
        map: map // 添加到地图实例中
      });
    }
  }
};
</script>

In the above code, replace it 你的高德地图 keywith your own Amap developer key. If you have not obtained the key, you need to go to the AutoNavi open platform ( https://lbs.amap.com ) to register and apply.

  1. Add a container for displaying the map in the template, and bind it to the map instance through the id.
<template>
  <div id="map-container"></div>
</template>
  1. Run the Vue project and view the page in a browser, you should be able to see a container containing a map with a marker point at its center.

This is just a simple example of displaying the map. You can further configure map parameters and add other functions according to your needs, such as zoom control, map type switching, etc. Please refer to the documentation of vue-amap ( https://elemefe.github.io/vue-amap/ ) to learn more about the functions and usage of vue-amap.

Please make sure that you have correctly applied for and obtained the Amap developer key, and fill it in according to actual needs. Also, remember to destroy map instances when appropriate to free up resources.

5 Map interaction

5.1 Marking annotations

To mark in a Vue project, you can use the Marker class provided by the JavaScript API of Gaode Maps.

Here's a simple example showing how to mark a location on the map:

<template>
  <div id="map-container"></div>
</template>

<script>
import {
      
       createApp } from 'vue';
import AMapJSAPILoader from '@amap/amap-jsapi-loader';

export default {
      
      
  mounted() {
      
      
    AMapJSAPILoader.load({
      
      
      key: '你的高德地图 key',
      version: '2.0',
      plugins: ['AMap.Geolocation']
    }).then(() => {
      
      
      this.initMap();
    });
  },
  methods: {
      
      
    initMap() {
      
      
      const map = new AMap.Map('map-container', {
      
      
        center: [116.397428, 39.90923],
        zoom: 13
      });

      // 创建标记点
      const marker = new AMap.Marker({
      
      
        position: [116.397428, 39.90923],
        title: '这里是标记点'
      });

      // 将标记点添加到地图中
      map.add(marker);
    }
  }
};
</script>

In the above code, replace it 你的高德地图 keywith your own Amap developer key. If you have not obtained the key, you need to go to the AutoNavi open platform ( https://lbs.amap.com ) to register and apply.

In initMapthe method, a map instance is created and a marker is added at the specified location. You can modify the position, title, etc. of the markers as needed.

Run the Vue project, view the page in a browser, and you should be able to see a map with markers at specified locations.

5.2 Map search function

To implement the map search function in the Vue project, you can use the search service and related APIs of AutoNavi Maps. Here's a simple example showing how to search on the map:

<template>
  <div>
    <div>
      <input v-model="keyword" placeholder="输入搜索关键字" />
      <button @click="search">搜索</button>
    </div>
    <div id="map-container"></div>
  </div>
</template>

<script>
import {
      
       createApp } from 'vue';
import AMapJSAPILoader from '@amap/amap-jsapi-loader';

export default {
      
      
  data() {
      
      
    return {
      
      
      keyword: '',
      map: null
    };
  },
  mounted() {
      
      
    AMapJSAPILoader.load({
      
      
      key: '你的高德地图 key',
      version: '2.0',
      plugins: ['AMap.Geolocation']
    }).then(() => {
      
      
      this.initMap();
    });
  },
  methods: {
      
      
    initMap() {
      
      
      this.map = new AMap.Map('map-container', {
      
      
        center: [116.397428, 39.90923],
        zoom: 13
      });
    },
    search() {
      
      
      if (this.keyword) {
      
      
        AMap.plugin('AMap.PlaceSearch', () => {
      
      
          const placeSearch = new AMap.PlaceSearch({
      
      
            map: this.map
          });

          // 根据关键字进行搜索
          placeSearch.search(this.keyword);
        });
      }
    }
  }
};
</script>

In the above code, replace it 你的高德地图 keywith your own Amap developer key. If you have not obtained the key, you need to go to the AutoNavi open platform ( https://lbs.amap.com ) to register and apply.

In the template, we use an input box and a button for entering search keywords and triggering the search action. When the search button is clicked, searchthe method is called to search the map.

searchThe method first checks to see keywordif there is a value, then AMap.PlaceSearchcreates a location search object using , and passes in the map instance. Then call searchthe method to search according to the keyword, and the search results will be displayed on the map.

Run the Vue project, view the page in the browser, you can enter keywords and click the search button to search the map.

5.3 Map event monitoring and processing

For map event monitoring and processing in the Vue project, you can use the event mechanism of Gaode Map to capture and process various user interaction events on the map.

Here is an example showing how to listen to and handle mouse click events on the map:

<template>
  <div id="map-container"></div>
</template>

<script>
import {
      
       createApp } from 'vue';
import AMapJSAPILoader from '@amap/amap-jsapi-loader';

export default {
      
      
  mounted() {
      
      
    AMapJSAPILoader.load({
      
      
      key: '你的高德地图 key',
      version: '2.0',
      plugins: ['AMap.Geolocation']
    }).then(() => {
      
      
      this.initMap();
    });
  },
  methods: {
      
      
    initMap() {
      
      
      const map = new AMap.Map('map-container', {
      
      
        center: [116.397428, 39.90923],
        zoom: 13
      });

      // 监听地图点击事件
      map.on('click', (event) => {
      
      
        const lnglat = event.lnglat; // 获取点击的经纬度坐标
        console.log('点击坐标:', lnglat);
      });
    }
  }
};
</script>

In the above code, replace it 你的高德地图 keywith your own Amap developer key. If you have not obtained the key, you need to go to the AutoNavi open platform ( https://lbs.amap.com ) to register and apply.

In initMapthe method, a map instance is created, and map.onthe click event of the map is listened to using the method. When a click event occurs, the callback function will be executed and an event object containing the latitude and longitude coordinates will be provided.

Run the Vue project and view the page in the browser. When you click the mouse on the map, the console will print out the corresponding latitude and longitude coordinates.

Remember to use the method to cancel event listening when the component is destroyed according to actual needs offto avoid memory leaks.

6 Advantages and limitations

6.1 Advantages of Vue and Gaode map integration

The integration of Vue and Gaode map has the following advantages:

  1. Responsive development: Vue is a popular responsive JavaScript framework that uses features such as virtual DOM and data binding to allow developers to easily build interactive user interfaces. Using Vue to integrate with Gaode Map can realize data interaction and state management between the map and other Vue components, and improve development efficiency.

  2. Component-based development: Vue supports component-based development, which can encapsulate maps and related functions into reusable components to improve code maintainability and reusability. Through componentization, map-related code can be better organized and the development process simplified.

  3. Strong Ecosystem: Vue has a large and active ecosystem with a rich library of plugins and extensions to choose from. When integrating with AutoNavi, you can use Vue plug-ins and third-party libraries to simplify map development and add additional functions, such as map search, trajectory drawing, positioning functions, etc.

  4. Flexible customization: Vue provides flexible data binding and componentization features, so that the integration with AutoNavi can be customized according to the needs of the project. You can customize the map style, interactive behavior, markers, layers, etc. on the map to meet the specific requirements of the project.

  5. Developer-friendly: Vue uses a simple and easy-to-understand API and declarative syntax, so you can get started quickly. AutoNavi provides detailed development documents and examples. Combined with the development method of Vue, developers can use the functions of AutoNavi more easily and quickly build feature-rich map applications.

The integration of Vue and Gaode Map can bring a more flexible, efficient and maintainable map development experience, while enjoying the respective advantages of the Vue framework and Gaode Map, improving development efficiency and user experience.

6.2 Limitations of integration of Vue and Gaode map

There are the following limitations in the process of Vue and Gaode map integration:

  1. Rely on third-party libraries: When Vue is integrated with AutoNavi, it is necessary to introduce the JavaScript API of AutoNavi and rely on the functions and limitations of the API. This may cause the application to need to be upgraded and adjusted in time when the Gaode map API is updated or is not compatible with the Vue version.

  2. Integration complexity: Since AutoNavi provides an independent JavaScript API, it may require some extra work to integrate with features such as Vue's data binding and life cycle. Developers are required to have certain front-end development experience and understanding of Vue and Gaode map API to achieve effective integration.

  3. Performance issues: AutoNavi Maps is a powerful map service that involves a large amount of geographic data and graphics rendering. In complex map applications, multiple interactions and data updates may be involved, which requires high performance. Developers need to optimize code to minimize unnecessary map refreshes and calculations to improve application performance.

  4. API restrictions and payment restrictions: The API usage of AutoNavi Maps may be subject to certain restrictions, such as request frequency, map display watermark, etc. In some cases, it may be necessary to purchase a premium API license for additional functionality and higher usage limits. Developers need to understand and meet the usage regulations and payment requirements of the Amap API.

While the integration of Vue and AutoNavi provides flexible and powerful map functions, developers also need to pay attention to the above limitations. Through reasonable planning and application design, developers can make full use of the advantages of Vue and AutoNavi, resolve limitations, and build efficient and reliable integrated applications.

Guess you like

Origin blog.csdn.net/weixin_55756734/article/details/131647031