1. Introduce the mapUtils.ts file of AutoNavi js
// make the map js API const gdApi = "https://webapi.amap.com/maps?v=2.0 & amp;key=Geocode key configured by yourself & amp;plugin=AMap.Geocoder"; export function initMap() {<!-- --> return new Promise((resolve, reject) => {<!-- --> loadScripts(gdApi, () => {<!-- --> resolve(false); }); }); } export function loadScripts(srcArr: any, callback: any) {<!-- --> let array: any[] = []; if (typeof srcArr === "string") {<!-- --> array = [srcArr]; } else if (Array.isArray(srcArr) & amp; & amp; srcArr.length > 0) {<!-- --> array = srcArr; } else {<!-- --> return; } //Get the loaded js on the page const scriptList = document. getElementsByTagName("script"); let scriptArr: any[] = []; for (let i = 0; i < scriptList. length; i ++ ) {<!-- --> scriptArr.push(scriptList[i].getAttribute("src")); } var loaderJs = (src, handler) => {<!-- --> //If it has been loaded before, skip it const hasNode = scriptArr. find((item) => item == src); if (hasNode) {<!-- --> handler & amp; & amp; handler(); return; } var script = document. createElement("script"); script.src = src; script.onload = () => {<!-- --> script.onload = null; handler(); }; script.onerror = () => {<!-- --> // After loading fails, you can continue to load the next js. console.log("Failed to load js:" + src); script.onload = null; handler(); }; var head = document. getElementsByTagName("head")[0]; (head || document.body).appendChild(script); }; (function run() {<!-- --> if (array. length != 0) {<!-- --> loaderJs(array. shift(), run); } else {<!-- --> callback & amp; & amp; callback(); } })(); }
2. Develop a map component
import React, {<!-- --> memo, useEffect, useState } from "react"; // public component import {<!-- --> Input, message } from "antd"; // Other files import {<!-- --> initMap } from "utils/mapUtils"; import cityData from "./city"; //All city js, because Gaode did not return the correct citycode of the city, so it matches the echo by itself import "./style.scss"; //style file let map: any = null; let marker: any = null; let placeSearch: any = null; let districtSearch: any = null; // Form input parameter type definition interface IProps {<!-- --> LngLat: any[]; //Longitude and latitude collection housingName: string; //echoed isChoose: boolean; cityKeywords: string; // administrative area name, citycode, adcode, business district name onConfirm: (item: any) => void; } // The popup box selects the item component const MapLocation: React.FC<IProps> = ({<!-- --> LngLat, housingName, isChoose, onConfirm, cityKeywords, }) => {<!-- --> const [lnglatString, setLnglatString] = useState<string>(""); const [address, setAddress] = useState<string>(""); const [housingEstateName, seHousingEstateName] = useState<string>(""); // const [addressInfo, setAddressInfo] = useState<any>({}); const [provinceCity, setProvinceCity] = useState<any>([]); // Enter to load the map useEffect(() => {<!-- --> initMap().then(() => {<!-- --> createMap(); }); }, []); // eslint-disable-line // Listen to the incoming city name and locate the center point of the map useEffect(() => {<!-- --> if ((!LngLat || LngLat.length <= 0) & amp; & amp; cityKeywords) {<!-- --> console.log(LngLat, "99999999999999"); setMapCurPos(); } }, [cityKeywords]); // eslint-disable-line // After listening to the selected point, pass it to the external component useEffect(() => {<!-- --> let outParams = {<!-- --> housingEstateName: housingEstateName, lnglatString: lnglatString, address: address, // addressInfo: addressInfo, provinceCity: provinceCity, }; onConfirm(outParams); }, [lnglatString, address]); // eslint-disable-line const createMap = () => {<!-- --> if (!AMap) {<!-- --> message.error("Map loading failed!"); return; } let mapParams: any = {<!-- --> zoom: 12 }; if (LngLat & amp; & amp; LngLat. length > 0) {<!-- --> mapParams.center = LngLat; mapParams. zoom = 14; } map = new AMap.Map("chooseAddressMapBox", mapParams); if (isChoose) {<!-- --> // map.on("click", (e) => {<!-- --> // console. log("e", e); // setMarkerShowAddress([e.lnglat.lng, e.lnglat.lat]); // }); } initSearchLnglat(); }; const initSearchLnglat = () => {<!-- --> AMap.plugin(["AMap.PlaceSearch", "AMap.DistrictSearch"], () => {<!-- --> //Initialize location query placeSearch = new AMap.PlaceSearch({<!-- --> map: map, panel: "result", pageSize: 5, extensions: "all", }); // //Click to select // placeSearch. listElementClick((data) => {<!-- --> // console.log(data, "66666666666"); // }); placeSearch.on("listElementClick", function (e) {<!-- --> console.log(e.data, "88888888"); //It contains all marker data let {<!-- --> cityname, location, pcode, adcode, pname, adname, address, name, } = e.data; let _index = cityData.findIndex((r) => r.areaName == cityname); if (_index != -1) {<!-- --> setProvinceCity([pcode, cityData[_index].areaCode, adcode]); } //setMarkerShowAddress([location.lng, location.lat]); setAddress(pname + cityname + adname + address); seHousingEstateName(name); setLnglatString(location.lng + "," + location.lat); }); //Initialize address prompt // var auto = new AMap. AutoComplete({<!-- --> // input: "tipinput", // }); // auto.search("Tiananmen", function (status, result) {<!-- --> // // When the search is successful, the result is the corresponding matching data // console. log(result); // }); // //Click to select // auto.on("select", (e) => {<!-- --> // //Register listener, it will be triggered when a record is selected // placeSearch.setCity(e.poi.adcode); // placeSearch.search(e.poi.name); //Keyword query query // setMarkerShowAddress([e.poi.location.lng, e.poi.location.lat]); // }); // Initialize city query districtSearch = new AMap.DistrictSearch({<!-- --> level: "city", }); }); }; const onchange = (e) => {<!-- --> seHousingEstateName(e.target.value); if (!e. target. value) return; placeSearch.search(e.target.value, function (status, result) {<!-- --> // When the query is successful, the result is the corresponding POI information console.log(result, "Gaode map returns the result"); }); }; const setMarkerShowAddress = (position: any[]) => {<!-- --> if (!position || position. length <= 0) return; if (!marker) {<!-- --> marker = new AMap. Marker(); } map. add(marker); marker. setPosition(position); map.setCenter(position); setLnglatString(position. join(",")); var geocoder = new AMap. Geocoder(); geocoder.getAddress(position, (status, result) => {<!-- --> console.log("result", result); if (status === "complete" & amp; & amp; result.regeocode) {<!-- --> setAddress(result. regeocode. formattedAddress); // setAddressInfo(result. regeocode); } else {<!-- --> console.log("Failed to query address based on latitude and longitude"); } }); }; // Query Gaode city information const setMapCurPos = () => {<!-- --> if (!districtSearch) return; districtSearch. search(cityKeywords, (status, result) => {<!-- --> const data = (result.districtList & amp; & amp; result.districtList[0]) || null; if (!data) return; const centerPos = [data. center. lng, data. center. lat]; const citycode = data.adcode; map.setCenter(centerPos); placeSearch.setCity(citycode); }); }; // Listen for incoming latitude and longitude changes, and map markers are updated useEffect(() => {<!-- --> if (map) {<!-- --> if (LngLat & amp; & amp; LngLat. length > 0) {<!-- --> placeSearch. clear(); seHousingEstateName(housingName); setMarkerShowAddress(LngLat); } else if (marker) {<!-- --> map. remove(marker); setLnglatString(""); setAddress(""); } } }, [LngLat]); // eslint-disable-line return ( <> <div className="edit_location_box"> <div id="chooseAddressMapBox" style={<!-- -->{<!-- --> height: 500 }}></div> <div className="address_info"> <div className="foldtxt">Latitude and longitude: {<!-- -->lnglatString}</div> <div className="foldtxt">Address: {<!-- -->address}</div> <div> <Input id="tipinput" value={<!-- -->housingEstateName} onChange={<!-- -->onchange} placeholder="Enter keyword query" /> </div> <div id="result"></div> </div> </div> </> ); }; export default memo(MapLocation);
style. scss
.edit_location_box {<!-- --> position: relative; .address_info {<!-- --> position: absolute; top: 0; left: 0; width: 300px; z-index: 100; padding: 10px; background-color: rgba($color: #fff, $alpha: 0.8); .foldtxt {<!-- --> font-weight: bold; font-size: 15px; color: #00004c; } } } .amap-sug-result {<!-- --> z-index: 3000 !important; }
on page reference
import {<!-- --> MapLocation } from "components"; <Modal title="Map Selection" open={<!-- -->mapVisible} onCancel={<!-- -->modalMapCancel} width={<!-- -->"60%"} forceRender={<!-- -->true} footer={<!-- --> <> <Button type="primary" onClick={<!-- -->modalMapConfirm} loading={<!-- -->loading}> Sure </Button> <Button type="default" onClick={<!-- -->modalMapCancel} loading={<!-- -->loading}> closure </Button> </> } > <MapLocation LngLat={<!-- -->LngLat} housingName={<!-- -->housingName.current} isChoose={<!-- -->true} cityKeywords={<!-- -->cityKeywords} onConfirm={<!-- -->mapConfirm} /> </Modal>
that’s all
renderings
If you need guidance, you can contact me on QQ 2981739544
Freelance Front End Development