# 扩展自定义组件

当你需要基于 AMap-Vue 开发更多自定义组件的时候,你可以通过内建的withAmap辅助 mixin,并将你的组件嵌套在<amap>组件内,就可以通过this.map访问到地图所关联的AMap.Map实例。

<script>
import { withAmap } from '@amap/amap-vue';

export default {
  name: 'MyCustomMapComponent',
  mixins: [withAmap],
  mounted() {
    this.$map; // 通过this.$map访问到外层的AMap.Map实例
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
<template>
  <amap>
    <!-- 任意层级嵌套 -->
    <my-custom-map-component />
  </amap>
</template>
1
2
3
4
5
6

这里是一个基本的例子,例中我们调用了this.$map.setFitViewthis.$map.setCenter方法,实现了 UI 与地图的简单联合交互。

<template>
  <div class="example-custom-extension">
    <amap
      :is-hotspot="false"
      :show-indoor-map="false"
      :center="[116.473778, 39.990661]"
      :zoom="13"
      map-style="amap://styles/whitesmoke"
    >
      <my-custom-map-component />
    </amap>
  </div>
</template>

<script>
import MyCustomMapComponent from './MyCustomMapComponent';

export default {
  components: { MyCustomMapComponent },
};
</script>

<style lang="less" scoped>
.example-custom-extension {
  width: 100%;
  height: 600px;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<template>
  <div class="my-custom-map-component">
    <amap-marker
      ref="markers"
      v-for="poi in results"
      :key="poi.id"
      :position="[poi.location.lng, poi.location.lat]"
      :label="{
        content: poi === hover ? poi.name : '',
        direction: 'bottom',
      }"
      :z-index="poi === hover ? 110 : 100"
      @mouseover="hover = poi"
      @mouseout="hover = null"
    />

    <a-card
      :head-style="{
        padding: '0 12px',
      }"
      :body-style="{
        'max-height': '450px',
        'overflow-y': 'scroll',
        padding: '0 12px 24px',
      }"
      class="result-panel"
    >
      <template slot="title">
        <template v-if="mode === 'search'">
          <a-input-group compact style="display: flex">
            <a-auto-complete
              v-model="query"
              :data-source="tips"
              placeholder="输入关键词"
              style="flex: 1"
              @search="autoComplete"
            />
            <a-button @click="search(true)" :disabled="!query" type="primary">
              搜索
            </a-button>
          </a-input-group>
        </template>
        <template v-if="mode === 'result'">
          <div class="result-title">
            <a-button icon="left" @click="reset" style="margin-right: 6px;" />
            <span class="count">共 {{ searching ? '...' : total }} 条结果</span>
          </div>
        </template>
      </template>

      <a-list
        v-if="mode === 'result'"
        :data-source="results"
        item-layout="vertical"
        size="small"
        class="result-list"
      >
        <a-pagination
          slot="header"
          v-if="total > 0"
          v-model="pageIndex"
          :page-size="pageSize"
          :total="total"
          size="small"
        />
        <a-list-item slot="renderItem" slot-scope="item" :key="item.id">
          <a-list-item-meta :description="item.address">
            <span slot="title" style="cursor: pointer;" @click="focus(item)">{{
              item.name
            }}</span>
          </a-list-item-meta>
        </a-list-item>
        <a-pagination
          slot="footer"
          v-if="total > 0"
          v-model="pageIndex"
          :page-size="pageSize"
          :total="total"
          size="small"
        />
      </a-list>
    </a-card>
  </div>
</template>

<script>
import { withAmap, loadPlugins } from '@amap/amap-vue';

export default {
  name: 'MyCustomMapComponent',
  mixins: [withAmap],
  data() {
    return {
      mode: 'search',
      query: '',
      searching: false,
      tips: [],
      results: [],
      total: 0,
      hover: null,
      position: null,
      pageIndex: 1,
      pageSize: 20,
    };
  },
  async mounted() {
    await loadPlugins(['AMap.AutoComplete', 'AMap.PlaceSearch']);
    this.ps = new AMap.PlaceSearch({
      pageSize: this.pageSize,
    });
    this.ac = new AMap.AutoComplete();
  },
  methods: {
    async search(clear = false) {
      this.mode = 'result';

      if (clear) {
        this.results = [];
        this.total = 0;
        this.pageIndex = 1;
        this.ps.setPageIndex(1);
      }

      this.searching = true;
      const { query } = this;
      this.ps.search(query, (status, result) => {
        this.searching = false;
        if (query !== this.query) return;

        if (status === 'complete' && result.poiList) {
          this.results = result.poiList.pois;
          this.total = result.poiList.count;
          this.fitView();
        } else {
          this.results = [];
          this.total = 0;
        }
      });
    },
    async autoComplete(kw) {
      if (!kw) {
        this.tips = [];
      } else {
        this.ac.search(kw, (status, result) => {
          if (kw !== this.query) return;
          if (status === 'complete' && result.tips) {
            this.tips = Array.from(new Set(result.tips.map(tip => tip.name)));
          } else {
            this.tips = [];
          }
        });
      }
    },
    focus(poi) {
      this.hover = poi;
      this.$map.setCenter([poi.location.lng, poi.location.lat]);
    },
    fitView() {
      requestAnimationFrame(() => {
        this.$map.setFitView(null, false, [0, 0, 300, 0]);
      });
    },
    reset() {
      this.ps.setPageIndex(1);
      this.results = [];
      this.tips = [];
      this.total = 0;
      this.mode = 'search';
    },
  },
  watch: {
    pageIndex(value) {
      this.ps.setPageIndex(value);
      this.search(false);
    },
  },
};
</script>

<style lang="less" scoped>
.my-custom-map-component {
  .result-panel {
    position: absolute;
    left: 10px;
    top: 10px;
    width: 280px;
    display: flex;
    flex-direction: column;

    .result-list {
      width: 100%;
    }

    .result-list.ant-list-loading {
      min-height: 100px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .result-title {
      .count {
        font-size: 14px;
        color: #999;
      }
    }
  }
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209