获取地名

在html中获取地名,格式如:“邯郸市火车站”,城市名+地名的形式

  1. //地图的父组件
  2. showLocationRequest(str) {
  3. let pramas = new FormData();
  4. pramas.append("address", str);
  5. this.http.post(this.hostUrl + 'Api/showLocation', pramas).subscribe(
  6. (response: Analysis) => {
  7. this.showLocationChange.next(response);
  8. }
  9. )
  10. }

接口

  1. http://www.mapocc.com/Api/showLocation/address/邯郸市火车站

image.png

  1. {
  2. status: 1,
  3. info: "返回成功",
  4. data: {
  5. coordinate: "36.631262731204,114.54562822824",
  6. 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}"
  7. }
  8. }

后台接口

ak、wk:就是用百度接口,申请的两个key

  1. public function showLocation($address = null) {
  2. $url = 'http://api.map.baidu.com/geocoder/v2/?address=' . $address . '&output=json&ak=' . self::ak;
  3. $info = self::getCurl($url);
  4. $infolist = json_decode($info);
  5. if (isset($infolist->result->location) && !empty($infolist->result->location)) {
  6. $array = array(
  7. 'lng' => $infolist->result->location->lng,
  8. 'lat' => $infolist->result->location->lat,
  9. );
  10. /*逆地理编码*/
  11. $location = $array['lat'] . ',' . $array['lng'];
  12. }
  13. //$location = $form[x] . ',' . $form[y];
  14. $url = 'http://api.map.baidu.com/geocoder/v2/?location=' . $location . '&output=json&pois=1&ak=' . self::ak;
  15. $info = self::getCurl($url);
  16. $infolist = json_decode($info, true);
  17. if (!empty($infolist['result']['poiRegions'])) {
  18. $tags = explode(';', $infolist['result']['poiRegions'][0]['tag']);
  19. $tag = $tags[0];
  20. $house = $infolist['result']['poiRegions'][0]['name'];
  21. $city = $infolist['result']['addressComponent']['city'];
  22. $line_info = $this->queryHouse($house, $city, $tag);
  23. $array_data = array();
  24. $array_data['coordinate'] = $location;
  25. $array_data['line_info'] = $line_info;
  26. if(!empty($line_info)){
  27. $this->ajaxReturnBlueMP(1, '返回成功', $array_data);
  28. }else{
  29. $this->ajaxReturnBlueMP(0, '返回失败', '');
  30. }
  31. }
  32. }
  33. private function queryHouse($house = null, $city = null, $tag = null) {
  34. $baseURL = 'http://api.map.baidu.com/place/v2/search?output=json&scope=2';
  35. $url = $baseURL . "&q=" . $house . "&region=" . $city . "&ak=" . self::wk;
  36. $info = self::getCurl($url);
  37. //p($info);
  38. $info_list = json_decode($info, true);
  39. if (!empty($info_list['results'])) {
  40. $uid = $info_list['results'][0]['uid'];
  41. }
  42. if ($uid) {
  43. $queryHouseOutline_baseURL = 'http://map.baidu.com/?reqflag=pcmap&coord_type=3&from=webmap&qt=ext&ext_ver=new&l=18';
  44. $queryHouseOutline_url = $queryHouseOutline_baseURL . '&uid=' . $uid;
  45. $line_info = self::getCurl($queryHouseOutline_url);
  46. return $line_info;
  47. }
  48. }

计算数据

  1. // 地图的父组件
  2. this.subscriptionLocation = this.analysisDataService.showLocationChange.subscribe(
  3. data => {
  4. this.showLocationData = data
  5. if (this.showLocationData.status == 1) {
  6. let mapdata = JSON.parse(this.showLocationData.data.line_info)
  7. this.calcPoint(mapdata)
  8. } else {
  9. this._toastrService.error(this.showLocationData.info);
  10. }
  11. }
  12. )
  13. calcPoint(data) {
  14. this.place = data.content.geo;
  15. this.pointmap = true;
  16. }

展示数据

  1. ngAfterViewInit() {
  2. //@ts-ignore
  3. this.map = new BMap.Map(this.mapId, {
  4. enableMapClick: false
  5. });
  6. this.map.centerAndZoom("北京市", 13);
  7. this.map.disableDragging();
  8. this.map.disableScrollWheelZoom();
  9. this.map.disableDoubleClickZoom();
  10. let mapStyle = { style: "dark" }
  11. this.map.setMapStyle(mapStyle);
  12. var geoPoint = this.mapService.parseGeo(this.place);
  13. //@ts-ignore
  14. var points = this.mapService.coordinateToPoints(this.map, geoPoint.points);
  15. console.log('points: ', points);
  16. //@ts-ignore
  17. var ply = new BMap.Polygon(points, {
  18. strokeWeight: 2,
  19. strokeColor: "#f35857",
  20. strokeOpacity: 0.8,
  21. fillColor: "transparent"
  22. }); //建立多边形覆盖物
  23. this.map.addOverlay(ply);
  24. setTimeout(() => {
  25. this.map.setViewport(ply.getPath()); //调整视野
  26. let e = this.map.getBounds(),
  27. t = e.getSouthWest(),
  28. a = e.getNorthEast();
  29. let range = {
  30. min_lng: t.lng,
  31. max_lng: a.lng,
  32. min_lat: t.lat,
  33. max_lat: a.lat
  34. }
  35. console.log(range)
  36. }, 1000)
  37. }
  1. /**
  2. * 墨卡托坐标解析
  3. * @param {} mocator
  4. * @return {}
  5. */
  6. parseGeo(mocator) {
  7. if (typeof mocator != 'string') {
  8. return {};
  9. }
  10. let t = mocator.split("|");
  11. let n = parseInt(t[0]);
  12. let i = t[1];
  13. let r = t[2];
  14. let o = r.split(";");
  15. if (n === 4) {
  16. for (var a = [], s = 0; s < o.length - 1; s++) {
  17. "1" === o[s].split("-")[0] && a.push(o[s].split("-")[1]);
  18. }
  19. o = a;
  20. o.push("");
  21. }
  22. let u: any = [];
  23. switch (n) {
  24. case 1:
  25. u.push(o[0]);
  26. break;
  27. case 2:
  28. case 3:
  29. case 4:
  30. for (var s = 0; s < o.length - 1; s++) {
  31. var l = o[s];
  32. if (l.length > 100) {
  33. 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,
  34. "$1,$2;");
  35. u.push(l);
  36. } else {
  37. for (var c = [], d = l.split(","), f = 0; f < d.length; f += 2) {
  38. var p = d[f];
  39. var h = d[f + 1];
  40. c.push(p + "," + h);
  41. }
  42. u.push(c.join(";"))
  43. }
  44. }
  45. break;
  46. default:
  47. break;
  48. }
  49. if (u.length <= 1) {
  50. u = u.toString();
  51. }
  52. var result = {
  53. type: n,
  54. bound: i,
  55. points: u
  56. };
  57. return result;
  58. };
  59. /**
  60. * 墨卡托坐标转百度坐标
  61. * @param {} coordinate
  62. * @return {}
  63. */
  64. coordinateToPoints(map, coordinate) {
  65. var points = [];
  66. if (coordinate) {
  67. var arr = coordinate.split(";");
  68. if (arr) {
  69. for (var i = 0; i < arr.length; i++) {
  70. var coord = arr[i].split(",");
  71. if (coord && coord.length == 2) {
  72. //@ts-ignore
  73. var mctXY = new BMap.Pixel(coord[0], coord[1]);
  74. var project = map.getMapType().getProjection();
  75. var point = project.pointToLngLat(mctXY);
  76. //@ts-ignore
  77. points.push(new BMap.Point(point.lng, point.lat));
  78. }
  79. }
  80. }
  81. }
  82. return points;
  83. };

完整jq代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
  6. <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ZX6UGVRcLVCVH30bgEx9bv5FOlr2rI5I">
  7. </script>
  8. <script src="../js/jquery-3.2.0.min.js"></script>
  9. <title>地图画圈</title>
  10. <style type="text/css">
  11. body {
  12. height: 100%;
  13. margin: 0px;
  14. padding: 0px;
  15. font-family: "微软雅黑";
  16. }
  17. #container {
  18. height: 500px;
  19. width: 100%;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <div id="container"></div>
  25. <div>
  26. <input id="area" type="text">
  27. <button id="getArea">获取</button>
  28. </div>
  29. </body>
  30. </html>
  31. <script type="text/javascript">
  32. //判断浏览区是否支持canvas
  33. if (!isSupportCanvas()) {
  34. alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
  35. }
  36. function isSupportCanvas() {
  37. var elem = document.createElement('canvas');
  38. return !!(elem.getContext && elem.getContext('2d'));
  39. }
  40. function setArea(str) {
  41. var geoPoint = parseGeo(str);
  42. var points = coordinateToPoints(map, parseGeo(str).points);
  43. var ply = new BMap.Polygon(points, {
  44. strokeWeight: 2,
  45. strokeColor: "#f35857",
  46. strokeOpacity: 0.8,
  47. fillColor: "transparent"
  48. });
  49. map.clearOverlays(); //清除地图上所有覆盖物
  50. map.addOverlay(ply); //建立多边形覆盖物
  51. map.setViewport(ply.getPath());
  52. }
  53. function getGeo(str) {
  54. $.ajax({
  55. type: 'POST',
  56. url: "http://www.mapocc.com/Api/showLocation",
  57. data: {
  58. address: str
  59. },
  60. success: function (data) {
  61. data = JSON.parse(data);
  62. let line_info = data.data.line_info;
  63. line_info = JSON.parse(line_info);
  64. let geo = line_info.content.geo;
  65. console.log('geo: ', geo);
  66. setArea(geo);
  67. },
  68. error: function (data) {}
  69. });
  70. }
  71. function parseGeo(mocator) {
  72. if (typeof mocator != 'string') {
  73. return {};
  74. }
  75. let t = mocator.split("|");
  76. let n = parseInt(t[0]);
  77. let i = t[1];
  78. let r = t[2];
  79. // let o = mocator.split(";");
  80. let o = r.split(";");
  81. if (n === 4) {
  82. for (var a = [], s = 0; s < o.length - 1; s++) {
  83. "1" === o[s].split("-")[0] && a.push(o[s].split("-")[1]);
  84. }
  85. o = a;
  86. o.push("");
  87. }
  88. let u = [];
  89. switch (n) {
  90. case 1:
  91. u.push(o[0]);
  92. break;
  93. case 2:
  94. case 3:
  95. case 4:
  96. for (var s = 0; s < o.length - 1; s++) {
  97. var l = o[s];
  98. if (l.length > 100) {
  99. l = l.replace(
  100. /(-?[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,
  101. "$1,$2;");
  102. u.push(l);
  103. } else {
  104. for (var c = [], d = l.split(","), f = 0; f < d.length; f += 2) {
  105. var p = d[f];
  106. var h = d[f + 1];
  107. c.push(p + "," + h);
  108. }
  109. u.push(c.join(";"))
  110. }
  111. }
  112. break;
  113. default:
  114. break;
  115. }
  116. if (u.length <= 1) {
  117. u = u.toString();
  118. }
  119. var result = {
  120. type: n,
  121. bound: i,
  122. points: u
  123. };
  124. return result;
  125. };
  126. function coordinateToPoints(map, coordinate) {
  127. var points = [];
  128. if (coordinate) {
  129. var arr = coordinate.split(";");
  130. if (arr) {
  131. for (var i = 0; i < arr.length; i++) {
  132. var coord = arr[i].split(",");
  133. if (coord && coord.length == 2) {
  134. //@ts-ignore
  135. var mctXY = new BMap.Pixel(coord[0], coord[1]);
  136. var project = map.getMapType().getProjection();
  137. var point = project.pointToLngLat(mctXY);
  138. //@ts-ignore
  139. points.push(new BMap.Point(point.lng, point.lat));
  140. }
  141. }
  142. }
  143. }
  144. return points;
  145. };
  146. var points = [];
  147. var map = new BMap.Map("container"); // 创建地图实例
  148. var point = new BMap.Point(116.418261, 39.921984);
  149. map.centerAndZoom(point, 15); // 初始化地图,设置中心点坐标和地图级别
  150. map.enableScrollWheelZoom(); // 允许滚轮缩放
  151. map.disableDoubleClickZoom();
  152. // 故宫
  153. var str =
  154. "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;"
  155. setArea(str);
  156. $(document).on('click', '#getArea', function () {
  157. getGeo($('#area').val())
  158. })
  159. </script>

结果

image.png
image.png
{“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}”}}