YanTianFeng的知识库

Want Coding

Want Reading

文章 89

访问 18442

评论 2

头像

YanTianFeng

发私信

文章 89
访问 18442
评论 2
Technology and Code
返回顶部

Knowledge  地图画区

标签   地图  

  ( 11 )       ( 0 )


地图画区代码实现

在 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 = data
    if (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-ignore
  this.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-ignore
  var points = this.mapService.coordinateToPoints(this.map, geoPoint.points);
  console.log('points: ', points);
  //@ts-ignore
  var 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-ignore
          var mctXY = new BMap.Pixel(coord[0], coord[1]);
          var project = map.getMapType().getProjection();
          var point = project.pointToLngLat(mctXY);
          //@ts-ignore
          points.push(new BMap.Point(point.lng, point.lat));
        }
      }
    }
  }
  return points;
};

结果