获取地名
在html中获取地名,格式如:“邯郸市火车站”,城市名+地名的形式
//地图的父组件showLocationRequest(str) {let pramas = new FormData();pramas.append("address", str);this.http.post(this.hostUrl + 'Api/showLocation', pramas).subscribe((response: Analysis) => {this.showLocationChange.next(response);})}
接口
http://www.mapocc.com/Api/showLocation/address/邯郸市火车站

{status: 1,info: "返回成功",data: {coordinate: "36.631262731204,114.54562822824",line_info: "{"content":{"geo":"4|12751236.7236,4362092.35239;12751404.5359,4362182.83531|1-12751241.5262,4362182.83531,12751404.5359,4362166.6619,12751399.7358,4362092.35239,12751236.7236,4362104.66658,12751241.5262,4362182.83531;","uid":"8a181d8dce36ebc884330470"},"current_city":{"code":1,"geo":"1|11590057.96,4489812.75;11590057.96,4489812.75|11590057.96,4489812.75;","level":0,"name":"\u4e2d\u56fd","sup":0,"sup_bus":0,"sup_business_area":0,"sup_lukuang":0,"sup_subway":0,"type":0,"up_province_name":"\u4e2d\u56fd"},"err_msg":"","hot_city":["\u5317\u4eac\u5e02|131","\u4e0a\u6d77\u5e02|289","\u5e7f\u5dde\u5e02|257","\u6df1\u5733\u5e02|340","\u6210\u90fd\u5e02|75","\u5929\u6d25\u5e02|332","\u5357\u4eac\u5e02|315","\u676d\u5dde\u5e02|179","\u6b66\u6c49\u5e02|218","\u91cd\u5e86\u5e02|132"],"result":{"data_security_filt_res":0,"error":0,"illegal":0,"qid":"","type":10,"uii_type":"china_main","region":"0","uii_qt":"poi_profile","login_debug":0},"uii_err":0}"}}
后台接口
ak、wk:就是用百度接口,申请的两个key
public function showLocation($address = null) {$url = 'http://api.map.baidu.com/geocoder/v2/?address=' . $address . '&output=json&ak=' . self::ak;$info = self::getCurl($url);$infolist = json_decode($info);if (isset($infolist->result->location) && !empty($infolist->result->location)) {$array = array('lng' => $infolist->result->location->lng,'lat' => $infolist->result->location->lat,);/*逆地理编码*/$location = $array['lat'] . ',' . $array['lng'];}//$location = $form[x] . ',' . $form[y];$url = 'http://api.map.baidu.com/geocoder/v2/?location=' . $location . '&output=json&pois=1&ak=' . self::ak;$info = self::getCurl($url);$infolist = json_decode($info, true);if (!empty($infolist['result']['poiRegions'])) {$tags = explode(';', $infolist['result']['poiRegions'][0]['tag']);$tag = $tags[0];$house = $infolist['result']['poiRegions'][0]['name'];$city = $infolist['result']['addressComponent']['city'];$line_info = $this->queryHouse($house, $city, $tag);$array_data = array();$array_data['coordinate'] = $location;$array_data['line_info'] = $line_info;if(!empty($line_info)){$this->ajaxReturnBlueMP(1, '返回成功', $array_data);}else{$this->ajaxReturnBlueMP(0, '返回失败', '');}}}private function queryHouse($house = null, $city = null, $tag = null) {$baseURL = 'http://api.map.baidu.com/place/v2/search?output=json&scope=2';$url = $baseURL . "&q=" . $house . "®ion=" . $city . "&ak=" . self::wk;$info = self::getCurl($url);//p($info);$info_list = json_decode($info, true);if (!empty($info_list['results'])) {$uid = $info_list['results'][0]['uid'];}if ($uid) {$queryHouseOutline_baseURL = 'http://map.baidu.com/?reqflag=pcmap&coord_type=3&from=webmap&qt=ext&ext_ver=new&l=18';$queryHouseOutline_url = $queryHouseOutline_baseURL . '&uid=' . $uid;$line_info = self::getCurl($queryHouseOutline_url);return $line_info;}}
计算数据
// 地图的父组件this.subscriptionLocation = this.analysisDataService.showLocationChange.subscribe(data => {this.showLocationData = dataif (this.showLocationData.status == 1) {let mapdata = JSON.parse(this.showLocationData.data.line_info)this.calcPoint(mapdata)} else {this._toastrService.error(this.showLocationData.info);}})calcPoint(data) {this.place = data.content.geo;this.pointmap = true;}
展示数据
ngAfterViewInit() {//@ts-ignorethis.map = new BMap.Map(this.mapId, {enableMapClick: false});this.map.centerAndZoom("北京市", 13);this.map.disableDragging();this.map.disableScrollWheelZoom();this.map.disableDoubleClickZoom();let mapStyle = { style: "dark" }this.map.setMapStyle(mapStyle);var geoPoint = this.mapService.parseGeo(this.place);//@ts-ignorevar points = this.mapService.coordinateToPoints(this.map, geoPoint.points);console.log('points: ', points);//@ts-ignorevar ply = new BMap.Polygon(points, {strokeWeight: 2,strokeColor: "#f35857",strokeOpacity: 0.8,fillColor: "transparent"}); //建立多边形覆盖物this.map.addOverlay(ply);setTimeout(() => {this.map.setViewport(ply.getPath()); //调整视野let e = this.map.getBounds(),t = e.getSouthWest(),a = e.getNorthEast();let range = {min_lng: t.lng,max_lng: a.lng,min_lat: t.lat,max_lat: a.lat}console.log(range)}, 1000)}
/*** 墨卡托坐标解析* @param {} mocator* @return {}*/parseGeo(mocator) {if (typeof mocator != 'string') {return {};}let t = mocator.split("|");let n = parseInt(t[0]);let i = t[1];let r = t[2];let o = r.split(";");if (n === 4) {for (var a = [], s = 0; s < o.length - 1; s++) {"1" === o[s].split("-")[0] && a.push(o[s].split("-")[1]);}o = a;o.push("");}let u: any = [];switch (n) {case 1:u.push(o[0]);break;case 2:case 3:case 4:for (var s = 0; s < o.length - 1; s++) {var l = o[s];if (l.length > 100) {l = l.replace(/(-?[1-9]\d*\.\d*|-?0\.\d*[1-9]\d*|-?0?\.0+|0|-?[1-9]\d*),(-?[1-9]\d*\.\d*|-?0\.\d*[1-9]\d*|-?0?\.0+|0|-?[1-9]\d*)(,)/g,"$1,$2;");u.push(l);} else {for (var c = [], d = l.split(","), f = 0; f < d.length; f += 2) {var p = d[f];var h = d[f + 1];c.push(p + "," + h);}u.push(c.join(";"))}}break;default:break;}if (u.length <= 1) {u = u.toString();}var result = {type: n,bound: i,points: u};return result;};/*** 墨卡托坐标转百度坐标* @param {} coordinate* @return {}*/coordinateToPoints(map, coordinate) {var points = [];if (coordinate) {var arr = coordinate.split(";");if (arr) {for (var i = 0; i < arr.length; i++) {var coord = arr[i].split(",");if (coord && coord.length == 2) {//@ts-ignorevar mctXY = new BMap.Pixel(coord[0], coord[1]);var project = map.getMapType().getProjection();var point = project.pointToLngLat(mctXY);//@ts-ignorepoints.push(new BMap.Point(point.lng, point.lat));}}}}return points;};
完整jq代码
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="initial-scale=1.0, user-scalable=no" /><script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ZX6UGVRcLVCVH30bgEx9bv5FOlr2rI5I"></script><script src="../js/jquery-3.2.0.min.js"></script><title>地图画圈</title><style type="text/css">body {height: 100%;margin: 0px;padding: 0px;font-family: "微软雅黑";}#container {height: 500px;width: 100%;}</style></head><body><div id="container"></div><div><input id="area" type="text"><button id="getArea">获取</button></div></body></html><script type="text/javascript">//判断浏览区是否支持canvasif (!isSupportCanvas()) {alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')}function isSupportCanvas() {var elem = document.createElement('canvas');return !!(elem.getContext && elem.getContext('2d'));}function setArea(str) {var geoPoint = parseGeo(str);var points = coordinateToPoints(map, parseGeo(str).points);var ply = new BMap.Polygon(points, {strokeWeight: 2,strokeColor: "#f35857",strokeOpacity: 0.8,fillColor: "transparent"});map.clearOverlays(); //清除地图上所有覆盖物map.addOverlay(ply); //建立多边形覆盖物map.setViewport(ply.getPath());}function getGeo(str) {$.ajax({type: 'POST',url: "http://www.mapocc.com/Api/showLocation",data: {address: str},success: function (data) {data = JSON.parse(data);let line_info = data.data.line_info;line_info = JSON.parse(line_info);let geo = line_info.content.geo;console.log('geo: ', geo);setArea(geo);},error: function (data) {}});}function parseGeo(mocator) {if (typeof mocator != 'string') {return {};}let t = mocator.split("|");let n = parseInt(t[0]);let i = t[1];let r = t[2];// let o = mocator.split(";");let o = r.split(";");if (n === 4) {for (var a = [], s = 0; s < o.length - 1; s++) {"1" === o[s].split("-")[0] && a.push(o[s].split("-")[1]);}o = a;o.push("");}let u = [];switch (n) {case 1:u.push(o[0]);break;case 2:case 3:case 4:for (var s = 0; s < o.length - 1; s++) {var l = o[s];if (l.length > 100) {l = l.replace(/(-?[1-9]\d*\.\d*|-?0\.\d*[1-9]\d*|-?0?\.0+|0|-?[1-9]\d*),(-?[1-9]\d*\.\d*|-?0\.\d*[1-9]\d*|-?0?\.0+|0|-?[1-9]\d*)(,)/g,"$1,$2;");u.push(l);} else {for (var c = [], d = l.split(","), f = 0; f < d.length; f += 2) {var p = d[f];var h = d[f + 1];c.push(p + "," + h);}u.push(c.join(";"))}}break;default:break;}if (u.length <= 1) {u = u.toString();}var result = {type: n,bound: i,points: u};return result;};function coordinateToPoints(map, coordinate) {var points = [];if (coordinate) {var arr = coordinate.split(";");if (arr) {for (var i = 0; i < arr.length; i++) {var coord = arr[i].split(",");if (coord && coord.length == 2) {//@ts-ignorevar mctXY = new BMap.Pixel(coord[0], coord[1]);var project = map.getMapType().getProjection();var point = project.pointToLngLat(mctXY);//@ts-ignorepoints.push(new BMap.Point(point.lng, point.lat));}}}}return points;};var points = [];var map = new BMap.Map("container"); // 创建地图实例var point = new BMap.Point(116.418261, 39.921984);map.centerAndZoom(point, 15); // 初始化地图,设置中心点坐标和地图级别map.enableScrollWheelZoom(); // 允许滚轮缩放map.disableDoubleClickZoom();// 故宫var str ="4|12957492.5276,4826153.61023;12958721.1443,4828041.10283|1-12957492.5276,4827968.34123,12957517.7271,4827978.71655,12957551.7012,4827985.70079,12957761.8414,4828001.08931,12958090.3003,4828010.18168,12958291.9749,4828022.30354,12958654.0221,4828041.10283,12958662.1553,4828035.30001,12958665.3908,4828016.49746,12958721.1443,4826620.84215,12958718.3665,4826607.98754,12958705.7846,4826595.30705,12958274.1406,4826576.04036,12958295.0962,4826161.28862,12958226.0039,4826158.83847,12958128.341,4826156.38524,12958047.0511,4826153.61023,12958044.7491,4826273.98684,12958026.0001,4826566.42516,12957796.4832,4826554.24398,12957566.8973,4826534.12694,12957551.4596,4826539.32662,12957547.5637,4826555.47632,12957492.5276,4827968.34123;"setArea(str);$(document).on('click', '#getArea', function () {getGeo($('#area').val())})</script>
结果


{“status”:1,”info”:”\u8fd4\u56de\u6210\u529f”,”data”:{“coordinate”:”39.987270075837,116.3448945207”,”line_info”:”{\”content\”:{\”geo\”:\”4|12951419.39,4836310.46;12951655.84,4836518.99|1-12951419.39,4836494.53,12951429.18,4836445.59,12951420.84,4836434.48,12951424.85,4836368.49,12951496.87,4836377.46,12951505.89,4836310.46,12951573.91,4836316.54,12951655.84,4836334.05,12951641.74,4836441.63,12951637.57,4836487.61,12951607.41,4836483.97,12951603.85,4836510.02,12951598.4,4836518.99,12951583.92,4836517.98,12951429.86,4836502.49,12951419.39,4836494.53;\”,\”uid\”:\”81cec255a85267f907fef5b9\”},\”current_city\”:{\”code\”:1,\”geo\”:\”1|11590057.96,4489812.75;11590057.96,4489812.75|11590057.96,4489812.75;\”,\”level\”:0,\”name\”:\”\u4e2d\u56fd\”,\”sup\”:0,\”sup_bus\”:0,\”sup_business_area\”:0,\”sup_lukuang\”:0,\”sup_subway\”:0,\”type\”:0,\”up_province_name\”:\”\u4e2d\u56fd\”},\”err_msg\”:\”\”,\”hot_city\”:[\”\u5317\u4eac\u5e02|131\”,\”\u4e0a\u6d77\u5e02|289\”,\”\u5e7f\u5dde\u5e02|257\”,\”\u6df1\u5733\u5e02|340\”,\”\u6210\u90fd\u5e02|75\”,\”\u5929\u6d25\u5e02|332\”,\”\u5357\u4eac\u5e02|315\”,\”\u676d\u5dde\u5e02|179\”,\”\u6b66\u6c49\u5e02|218\”,\”\u91cd\u5e86\u5e02|132\”],\”result\”:{\”data_security_filt_res\”:0,\”error\”:0,\”illegal\”:0,\”qid\”:\”\”,\”type\”:10,\”uii_type\”:\”china_main\”,\”region\”:\”0\”,\”uii_qt\”:\”poi_profile\”,\”login_debug\”:0},\”uii_err\”:0}”}}
