在react中使用原生的高德地圖


1、使用react-create-app創建一個新的react項目

2、修改index.html,添加以下script引用:

 

3、創建一個組件文件MapDemo.js,內容如下

import React, { Component } from "react";

class WebMapDemo extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount(){
        var map = new AMap.Map('container', {
            viewMode: '3D',
            pitch: 50,
            zoom: 11,
            center: [116.480766, 39.932931]
        });
    
        // 設置光照
        map.AmbientLight = new AMap.Lights.AmbientLight([1, 1, 1], 0.5);
        map.DirectionLight = new AMap.Lights.DirectionLight([0, 0, 1], [1, 1, 1], 1);
    
        var object3Dlayer = new AMap.Object3DLayer();
        map.add(object3Dlayer);
    
        new AMap.DistrictSearch({
            subdistrict: 0,   //返回下一級行政區
            extensions: 'all',  //返回行政區邊界坐標組等具體信息
            level: 'city'  //查詢行政級別為 市
        }).search('朝陽區', function (status, result) {
            var bounds = result.districtList[0].boundaries;
            var height = 5000;
            var color = '#0088ffcc'; // rgba
            var prism = new AMap.Object3D.Prism({
                path: bounds,
                height: height,
                color: color
            });
    
            prism.transparent = true;
            object3Dlayer.add(prism);
    
            var text = new AMap.Text({
                text: result.districtList[0].name + '</br>(' + result.districtList[0].adcode + ')',
                verticalAlign: 'bottom',
                position: [116.528261, 39.934313],
                height: 5000,
                style: {
                    'background-color': 'transparent',
                    '-webkit-text-stroke': 'red',
                    '-webkit-text-stroke-width': '0.5px',
                    'text-align': 'center',
                    'border': 'none',
                    'color': 'white',
                    'font-size': '24px',
                    'font-weight': 600
                }
            });
    
            text.setMap(map);
        });
    }

    render() {
        return (
            <div id="container" style ={{width:"100%",height:"95%"}}>                
            </div>
        );
    }

}

export default WebMapDemo;

注意AMap類不是react中定義的類,會在運行時報錯,因此需要參考我的另一篇隨筆 《配合react-amap使用原生高德地圖》, 將AMap類排除在eslint語法檢查之外。

 

4、編寫index.js,加載在3里編寫的這個地圖組件

import React from "react";
import ReactDOM from "react-dom";
import Map from "./MapDemo";

ReactDOM.render(
    <div style ={{width:"100%",height:"100%"}}>    
        <Map />
    </div>,

    document.getElementById("root")
);

  

5、執行 npm start運行項目:

完工。

 

6 說明

為了講清邏輯, 地圖的創建和操作都寫在了componentDidMount里面。各位自行進行性能優化。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM