WebGIS之实现查询地区天气并让地区高亮

一.预览>>


 

二.思路>>


        根据搜索框的内容来进行页面视角的切换,对应的地区高亮,右边有关天气的地方实时更新,并且因为代码体量非常小,并没有选择在框架下完成。直接一个html文件搞定了,但实际上还是有一些坑的,比如不太了解的人会把key引入错,关于请求高德接口方面,注意阅读看是否需要其它参数,地理/逆地理编码-基础 API 文档-开发指南-Web服务 API|高德地图API (amap.com)icon-default.png?t=N7T8https://lbs.amap.com/api/webservice/guide/api/georegeo可能之后时间过得久了,对应API发生了变化,及时查阅文档。

三.代码>> 


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather</title>
    <link href="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.css" rel="stylesheet">
    <script src="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        #header {
            width: 100%;
            height: 100px;
            background-color: #212121;
            overflow: hidden;
            /* 解决margin塌陷,因为group设置了margin-top*/
        }

        #map {
            width: 100%;
            position: absolute;
            top: 100px;
            bottom: 0;
        }

        #map .information {
            padding: 0;
            margin: 0;
            list-style: none;
            width: 200px;
            height: 300px;
            position: absolute;
            z-index: 1;
            top: 10px;
            right: 10px;
            color: #fff;

            background-color: rgba(0, 0, 0, 0.4);
            border-radius: 5px;
            padding: 10px;
            display: flex;
            align-items: stretch;
            justify-content: space-around;
            flex-direction: column;
        }

        #map .information li {
            border-bottom: 1px solid aqua;
            font-style: 20px;
        }


        .group {
            display: flex;
            line-height: 28px;
            align-items: center;
            position: relative;
            max-width: 190px;
            margin: 0 auto;
            margin-top: 20px;
        }

        .input {
            width: 100%;
            height: 40px;
            line-height: 28px;
            padding: 0 1rem;
            padding-left: 2.5rem;
            border: 2px solid transparent;
            border-radius: 8px;
            outline: none;
            background-color: #f3f3f4;
            color: #0d0c22;
            transition: .3s ease;
        }

        .input::placeholder {
            color: #9e9ea7;
        }

        .input:focus,
        input:hover {
            outline: none;
            border-color: rgba(234, 76, 137, 0.4);
            background-color: #fff;
            box-shadow: 0 0 0 4px rgb(234 76 137 / 10%);
        }

        .icon {
            position: absolute;
            left: 1rem;
            fill: #9e9ea7;
            width: 1rem;
            height: 1rem;
        }
    </style>
</head>

<body>
    <div id="header">
        <!-- <input type="text" placeholder="请输入城市名称"> -->
        <div class="group">
            <svg class="icon" aria-hidden="true" viewBox="0 0 24 24">
                <g>
                    <path
                        d="M21.53 20.47l-3.66-3.66C19.195 15.24 20 13.214 20 11c0-4.97-4.03-9-9-9s-9 4.03-9 9 4.03 9 9 9c2.215 0 4.24-.804 5.808-2.13l3.66 3.66c.147.146.34.22.53.22s.385-.073.53-.22c.295-.293.295-.767.002-1.06zM3.5 11c0-4.135 3.365-7.5 7.5-7.5s7.5 3.365 7.5 7.5-3.365 7.5-7.5 7.5-7.5-3.365-7.5-7.5z">
                    </path>
                </g>
            </svg>
            <input placeholder="输入城市名称" type="search" class="input">
        </div>
    </div>
    <div id="map">
        <ul class="information">
            <li>当前时间</li>
            <li>城市</li>
            <li>天气</li>
            <li>温度</li>
            <li>风向</li>
            <li>风力</li>
        </ul>
    </div>

    <script type="text/javascript">
        window._AMapSecurityConfig = {
            securityJsCode: "写你自己的",
        };
    </script>
    <script type="text/javascript"
        src="https://webapi.amap.com/maps?v=2.0&key=你自己的web端key">        </script>
    <script>
        const input = document.querySelector('.input');
        mapboxgl.accessToken = 'pk.eyJ1IjoiY3VkODUiLCJhIjoiY2xrYnFncXZhMGc1cTNlbmFrNHN1N2cxeCJ9.69E3f8nMJkvqQDRhLSojVw';
        const map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/mapbox/streets-v12',
            zoom: 10,
            center: [116.41667, 39.91667]
        });


        document.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                const cityName = input.value;
                //使用完清空,便于下次使用
                input.value = ''
                queryWeather(cityName)
            }
        })

        function queryWeather(cityName) {
            //加载天气查询插件,因为只展示当前天气,没必要调用接口
            AMap.plugin("AMap.Weather", function () {
                //创建天气查询实例
                var weather = new AMap.Weather();
                //执行实时天气信息查询
                weather.getLive(cityName, function (err, data) {
                    console.log(data);
                    if (!err) {
                        updateWeatherInfo(data)
                        updateMap(data.city, data.adcode)
                    } else {
                        alert(err)
                    }
                });
            });
        }

        function updateWeatherInfo(data) {
            const timeElement = document.querySelector('.information li:nth-child(1)')
            const cityElement = document.querySelector('.information li:nth-child(2)');
            const weatherElement = document.querySelector('.information li:nth-child(3)');
            const tempElement = document.querySelector('.information li:nth-child(4)');
            const windDirectionElement = document.querySelector('.information li:nth-child(5)');
            const windPowerElement = document.querySelector('.information li:nth-child(6)');

            timeElement.textContent = '当前时间:' + data.reportTime;
            cityElement.textContent = '城市:' + data.city;
            weatherElement.textContent = '天气:' + data.weather;
            tempElement.textContent = '温度:' + data.temperature + '°C';
            windDirectionElement.textContent = '风向:' + data.windDirection;
            windPowerElement.textContent = '风力:' + data.windPower + '级';
        }

        function updateMap(city, adcode) {
            //调用高德的地理编码API
            //记住是这个key绑定的是Web服务,跟前面的key不是一种
            axios({
                url: `https://restapi.amap.com/v3/geocode/geo?address=${city}&adcode=${adcode}&key=填自己的key`
            }).then(result => {
                // console.log(typeof (result.data.geocodes[0].location))  //String类型
                var locationString = result.data.geocodes[0].location;
                var coordinates = locationString.split(","); // 经度和纬度之间用逗号分隔,可以根据实际情况调整分隔符

                // 创建一个新的 LngLat 对象
                var newCenter = new mapboxgl.LngLat(parseFloat(coordinates[0]), parseFloat(coordinates[1]));

                //实现视角跳转
                map.flyTo({
                    center: newCenter,
                    //使动画平滑
                    essential: true
                })
            }).catch(error => {
                console.log(error.message);
            })

            // 先检查是否已存在同名的数据源和图层,如果存在,则移除
            if (map.getSource('json')) {
                map.removeLayer('place'); // 移除图层
                map.removeSource('json'); // 移除数据源
            }

            //省市的url带有_full,观察adcode的区别来确定模板字符串
            let url = ''
            if (adcode[adcode.length - 1] == 0) {
                url = `https://geo.datav.aliyun.com/areas_v3/bound/${adcode}_full.json`
            } else {
                url = `https://geo.datav.aliyun.com/areas_v3/bound/${adcode}.json`
            }

            // console.log(url);
            map.addSource('json', {
                type: 'geojson',
                data: url
            })
            map.addLayer({
                id: 'place',
                type: 'fill',
                source: 'json',
                paint: {
                    'fill-color': '#ff5733', // 设置填充颜色为橙红色
                    'fill-opacity': 0.5, // 设置填充不透明度
                    'fill-outline-color': '#ffffff', // 设置边界线的颜色为白色
                    'fill-outline-width': 2 // 设置边界线的宽度
                }
            })
        }

    </script>
</body>

</html>

         

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WebGIS查询和路径规划功能的实现源代码涉及的技术和工具比较复杂,这里无法提供完整的代码实现。但是,我可以为你提供一些实现该功能所需的基本步骤和示例代码: 1. 查询功能实现步骤: - 创建查询表单,包括输入框、下拉框等控件,用于用户输入查询条件。 - 根据用户输入的条件,构造查询语句,向WebGIS中的数据源发起查询请求。 - 解析查询结果,将符合条件的数据在地图上进行标注或高亮显示。 下面是一个使用ArcGIS API for JavaScript实现查询功能的示例代码: ```javascript var queryTask = new QueryTask("http://yourserver/yourmapserver/0"); var query = new Query(); query.returnGeometry = true; query.outFields = ["*"]; query.where = "name LIKE '%" + searchTerm + "%'"; queryTask.execute(query, showResults); function showResults(results) { var featureSet = results.featureSet; for (var i = 0; i < featureSet.features.length; i++) { var feature = featureSet.features[i]; // 在地图上标注或高亮显示查询结果 } } ``` 2. 路径规划功能实现步骤: - 获取起点和终点的位置信息。 - 调用路径规划API,将起点和终点的位置信息作为参数发起请求。 - 解析路径规划结果,将路径在地图上进行绘制或高亮显示。 下面是一个使用百度地图API实现路径规划功能的示例代码: ```javascript var startPoint = new BMap.Point(116.404, 39.915); var endPoint = new BMap.Point(116.426, 39.915); var transit = new BMap.TransitRoute(map, { renderOptions: { map: map, panel: "results" } }); transit.search(startPoint, endPoint); ``` 以上示例代码仅供参考,具体实现方式需要根据具体的应用场景和技术选型进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值