react实现高德地图POI关键字搜索地点
时间: 2024-09-23 22:01:53 浏览: 226
在React中使用高德地图实现POI(Point of Interest,兴趣点)关键字搜索功能,通常需要以下几个步骤:
1. **安装依赖**:首先,你需要引入`amap-react`库,它包含了高德地图的React组件。你可以通过npm安装:
```
npm install amap-react amap-jsapi-loader
```
2. **加载AMAP API**:在项目中导入并使用`script-loader`将高德地图API动态加载到页面上:
```jsx
import { loadAMAP } from 'amap-jsapi-loader';
useEffect(() => {
loadAMAP().then(() => {
// 加载完成后的回调
});
}, []);
```
3. **创建Map组件**:创建一个React组件,包含地图容器、设置初始位置和地图选项:
```jsx
const MapWithSearch = () => {
const [map, setMap] = useState(null);
const [searchText, setSearchText] = useState('');
// 地图初始化配置
const initOptions = {
zoom: 12,
center: [116.404, 39.915], // 北京坐标
};
// 搜索事件处理函数
const onSearch = (result) => {
if (result && result.poiList) {
// 根据返回结果更新地图标记
result.poiList.forEach((poi) => {
map.setCenter(poi.location);
addMarker(poi);
});
}
};
// 添加标记函数
const addMarker = (poi) => {
new AMap.Marker({
position: poi.location,
infoWindow: new AMap.InfoWindow({ content: poi.name }),
raiseOnDrag: true,
draggable: false,
}).addTo(map);
};
return (
<div>
{/* ... */}
<AMap.Map
ref={(ref) => setMap(ref)}
onSearch={onSearch}
amapkey="your_amap_key"
options={initOptions}>
</AMap.Map>
<input type="text" value={searchText} onChange={(e) => setSearchText(e.target.value)} />
</div>
);
};
```
4. **发起搜索请求**:使用`AMap.search`方法,传入关键词和查询类型(如POI):
```jsx
<AMap.Search
onSearch={(params, response) =>
onSearch(response.poi)
}
searchWord={searchText}
autoType="POI"
city="北京"
/>
```
5. **样式和组件组织**:最后,按照需要调整样式,并组合MapWithSearch组件与其他内容。
阅读全文
相关推荐


















