1.首先现在现在public引入密钥
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>logo.ico">
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode:'你的安全密钥',
}
</script>
<script src = 'https://webapi.amap.com/maps?v=2.0&key=你的key&&plugin=AMap.Scale,AMap.HawkEye,AMap.ToolBar,AMap.ControlBar,AMap.PlaceSearch,AMap.DistrictSearch,AMap.HeatMap,AMap.3DTilesLayer,AMap.IndoorMap,AMap.MoveAnimation,AMap.ElasticMarker,AMap.MarkerCluster,AMap.IndexCluster,AMap.MouseTool,AMap.BezierCurveEditor,AMap.RectangleEditor,AMap.CircleEditor,AMap.EllipseEditor,AMap.GeoJSON,AMap.PolylineEditor,AMap.PolygonEditor,AMap.AutoComplete,AMap.Driving,AMap.Walking,AMap.Riding,AMap.Transfer,AMap.Geocoder,AMap.GraspRoad,AMap.StationSearch,AMap.LineSearch,AMap.ArrivalRange,AMap.CitySearch,AMap.Geolocation,AMap.Weather,AMap.RangingTool'></script>
<script type="text/javascript" src='https://a.amap.com/jsapi_demos/static/data3d/lib/three.117.js'></script>
<script type="text/javascript" src='https://a.amap.com/jsapi_demos/static/data3d/lib/GLTFLoader.117.min.js'></script>
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
2.引入 vue组件
<template>
<div class="app-container" :style="{ height: windowHeight - 50 + 'px' }">
<div class="header">
<el-form inline>
<!-- 起点输入框 -->
<el-form-item label="起点:" prop="startAddress">
<el-input
class="serach1"
v-model="startAddress"
placeholder="请输入起点地址"
></el-input>
</el-form-item>
<!-- 终点输入框 -->
<el-form-item label="终点:" prop="endAddress">
<el-input
ref="endInput"
class="serach1"
v-model="endAddress"
id="end_autocomplete_input"
placeholder="请输入终点地址"
></el-input>
</el-form-item>
<!-- 规划路线按钮 -->
<el-button
class="button primary-action"
type="primary"
@click="planRoute"
>规划路线</el-button>
</el-form>
</div>
<div class="map-and-panel-container">
<div id="container" class="map"></div>
<div id="panel" class="route-result-panel">
</div>
</div>
</div>
</template>
<script>
export default {
name: "index",
// head: {
// script: [{src:'./amap-config.js'}]
// },
data() {
return {
//实时屏幕高度
windowHeight: this.windowHeight,
map: null,
address: '',
startAddress: "",
endAddress: "",
status: '', // 添加用来记录定位状态的字段
result: '', // 这里用于存储详细的定位信息
city: '',
};
},
mounted() {
// 当浏览器被重置大小时执行
window.onresize = () => {
return (() => {
if (process.client) {
this.windowHeight = document.documentElement.clientHeight;
return this.windowHeight;
}
})();
};
this.initAMap2() ;
// 调用地图初始化方法
this.initmap1();
},
methods: {
initAMap2() {
let that = this;
// 基本地图加载
let map = new AMap.Map("container", {
resizeEnable: true,
center: "", // 地图中心点
zoom: 13, // 地图显示的缩放级别
});
},
initmap1() {
const map = new AMap.Map("container", { zoom: 10, resizeEnable: true });
// 定位成功后更新地图中心点
const updateMapCenter = (location) => {
map.setCenter(location.position);
// 如果需要调整缩放级别,可以使用:
// map.setZoom(15); // 或其他适合的缩放级别
};
// 地图定位功能
AMap.plugin("AMap.Geolocation", async function () {
const geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
timeout: 10000, // 超过10秒后停止定位,默认:无穷大
showButton: true, // 显示定位按钮,默认:true
convert: true,
buttonPosition: 'LB', // 定位按钮停靠位置,默认:'LB',左下角
buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
showMarker: true, // 定位成功后在定位到的位置显示点标记,默认:true
panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
needAddress: true,
useNative: true,
noIpLocate: 0,
zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
});
map.addControl(geolocation);
geolocation.getCurrentPosition((status, result) => {
if (status === "complete") {
this.onLocationSuccess(result);
updateMapCenter(result);
} else {
this.onLocationError(result);
}
});
});
// 输入提示功能
AMap.plugin("AMap.AutoComplete", function () {
var autoOptions = {
input: "end_autocomplete_input", // 使用上面添加的终点输入框ID
};
var autoComplete = new AMap.AutoComplete(autoOptions);
// 绑定选择事件并确保`this`指向Vue组件实例
autoComplete.on('select', function (e) {
this.endAddress = e.poi.name; // 更新终点地址
}.bind(this));
});
},
onLocationSuccess(result) {
this.result = result;
this.startAddress = this.result.formattedAddress;
console.log(this.result.formattedAddress);
console.log('定位成功:', result);
this.status = "定位成功";
// 提取并保存城市名称
this.city = result.addressComponent ? result.addressComponent.city : '';
console.log(this.city);
// 将整个定位结果也存入result变量
this.result = JSON.stringify(result, null, 2);
},
onLocationError(result) {
console.error('定位失败:', result);
this.status = "定位失败";
this.result = JSON.stringify(result, null, 2); // 记录错误信息
},
initAMap() {
let that = this;
// 基本地图加载
let map = new AMap.Map("container", {
resizeEnable: true,
center: "", // 地图中心点
zoom: 13, // 地图显示的缩放级别
});
console.log("地图已经初始化");
// 构造路线导航类
let driving = new AMap.Driving({
map: map,
panel: "panel",
});
// 根据起终点名称规划驾车导航路线
driving.search([
{ keyword: this.startAddress },
{ keyword: this.endAddress },
], function (status, result) {
// result 即是对应的驾车导航信息,相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
if (status === "complete") {
that.$message({
message: "绘制驾车路线完成",
type: "success",
});
} else {
that.$message.error("获取驾车数据失败" + result);
}
});
},
showWeatherInfo(data) {
this.$alert(
`<div>城市:${data.forecast.location.name}<br/>
实时天气:${data.now.text}<br/>
温度:${data.now.temperature}<br/>
风向风力:${data.now.wind_direction} ${data.now.wind_power}<br/>
//...更多要展示的天气信息...
`,
"天气预报",
{
dangerouslyUseHTMLString: true,
confirmButtonText: "关闭",
customClass: "weather-popup", // 自定义样式类名,可以根据需要设置弹窗样式
closeOnClickModal: false, // 点击模态框背景时不关闭弹窗
offset: "100px", // 设置弹窗位置偏移,使其更靠近右上角
}
);
},
// 获取并显示天气信息
getAndDisplayWeather() {
AMap.plugin("AMap.Weather", function () {
var weather = new AMap.Weather();
console.log("天气已经调用");
weather.getForecast(this.endAddress, (err, data) => {
if (!err) {
console.log(data);
this.showWeatherInfo(data.forecast);
console.log(data.data.forecast);
} else {
console.error("获取天气信息失败", err);
this.$message.error("获取天气信息失败");
}
});
}.bind(this));
},
planRoute() {
if (!this.startAddress || !this.endAddress) {
this.$message.error("请输入起点和终点地址");
return;
}
this.getAndDisplayWeather();
this.initAMap();
},
},
};
</script>
<style scoped>
.app-container {
width: 100%;
position: relative;
display: flex;
flex-direction: column;
align-items: stretch;
}
.header {
background-color: #f5f7fa;
border-bottom: 0.5px solid #f5f6fa;
}
.map-and-panel-container {
display: flex;
width: 100%;
height: calc(100% - 5rem);
overflow: hidden;
}
.map {
flex-grow: 1;
width: 70%;
height: 100%;
}
.route-result-panel {
width: 30%;
height: 100%;
background-color: white;
overflow-y: auto;
padding: 1rem;
}
.serach1 {
width: 200px;
}
.primary-action {
margin-left: 1rem;
}
</style>