Weex开发之地图篇的具体使用

在移动应用开发中,地图是一个很重要的工具,基于地图的定位、导航等特点衍生出了很多著名的移动应用。在Weex开发中,如果要使用定位、导航和坐标计算等常见的地图功能,可以使用weex-amap插件。

weex-amap是高德针对Weex开发的一款地图插件,在Eros开发中,Eros对weex-amap进行二次封装,以便让开发者更集成地图功能。和其他的插件一样,集成此插件需要在原生平台中进行集成。

本文介绍的是如何在iOS中集成weex-amap,以及它的一些核心功能。本文将要介绍的内容如下:

1.高德地图开发准备工作

  • 1.1 iOS高德地图开发流程简单介绍
  • 1.2 android高德地图开发流程简单介绍
  • 1.3 web高德地图开发流程简单介绍

2. weex-iOS地图组件扩展方式介绍

  • 2.1 dwd-weex-amap
  • 2.2 dwd-weex-amap-marker
  • 2.3 dwd-weex-amap-info-window
  • 2.4 dwd-weex-amap-circle
  • 2.5 dwd-weex-amap-polygon
  • 2.5 dwd-weex-amap-polyline

3.weex-android地图组件扩展方式介绍

  • 3.1 dwd-weex-amap
  • 3.2 dwd-weex-amap-marker
  • 3.3 dwd-weex-amap-info-window
  • 3.4 dwd-weex-amap-circle
  • 3.5 dwd-weex-amap-polygon
  • 3.6 dwd-weex-amap-polyline

4.weex-html5地图组件扩展方式介绍

  • 4.1 dwd-weex-amap
  • 4.2 dwd-weex-amap-marker
  • 4.3 dwd-weex-amap-info-window
  • 4.4 dwd-weex-amap-circle
  • 4.5 dwd-weex-amap-polygon
  • 4.6 dwd-weex-amap-polyline

5.获取地图数据(例如骑行路径规划)

  • 5.1 weex-iOS地图骑行路径规划
  • 5.2 weex-android地图骑行路径规划
  • 5.3 weex-web地图骑行路径规划

准备工作

1.1 开发流程简绍

1.使用 CocoaPods 安装AMapSearch,AMap3DMap SDK
2.前往高德开放平台控制台申请 iOS Key
3.配置高德Key至AppDelegate.m文件

1.2 android高德地图开发流程简绍

1.使用 CocoaPods 安装AMapSearch,AMap3DMap SDK
2.前往高德开放平台控制台申请 android Key
3.AndroidManifest.xml的application标签中配置Key
4.AndroidManifest.xml中配置权限

1.3 HTML5高德地图开发流程简绍

1.前往高德开放平台控制台申请 jsAPI Key
2.可通过CDN同步加载方式或使用require异步方式来加载key

参考:高德地图开发文档vue-amap开发文档

weex-iOS地图组件扩展

2.1 weex-amap

地图展示是地图最基本的功能,其常见的效果如下:

如有要在iOS中自定义weex-amap可以从以下几个步骤完成:

1.新建DMapViewComponent类继承WXComponent;
2.在DMapViewComponent实现文件中实现MAMapViewDelegate代理;
3. 重写DMapViewComponent的loadView方法加载地图视图并设置自身为代理对象;
4.在DMapViewComponent的初始化函数viewDidLoad中做一些准备工作;
5.在DMapViewComponent的initWithRef方法中实现属性绑定;
6.通过fireEvent添加适当时机可以触发的事件;
7.重写insertSubview方法来添加子组建包括覆盖物,线,圆等等。

下面是部分的业务实现代码:

@implementation DMapViewComponent
...
// 属性绑定
- (instancetype)initWithRef:(NSString *)ref
            type:(NSString*)type
           styles:(nullable NSDictionary *)styles
         attributes:(nullable NSDictionary *)attributes
           events:(nullable NSArray *)events
        weexInstance:(WXSDKInstance *)weexInstance
{
  self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance];
  if (self) {
    // 中心点
    NSArray *center = [attributes map_safeObjectForKey:@"center"];
    _zoomLevel = [[attributes map_safeObjectForKey:@"zoom"] floatValue];
    // 是否允许显示指南针
    _compass = [[attributes map_safeObjectForKey:@"compass"] boolValue];
    // sdkKey
    if ([attributes map_safeObjectForKey:@"sdkKey"]) {
      [self setAPIKey:[attributes[@"sdkKey"] objectForKey:@"ios"] ? : @""];
    }
...
  }
  return self;
}
// 重写DMapViewComponent的loadView方法加载地图视图并设置自身为代理对象
- (UIView *) loadView
{
  UIWindow *window = [UIApplication sharedApplication].keyWindow;
  CGSize windowSize = window.rootViewController.view.frame.size;
  self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, windowSize.width, windowSize.height)];
  self.mapView.showsUserLocation = _showGeolocation;
  self.mapView.delegate = self;
  self.mapView.customMapStyleEnabled = YES;
  [self.mapView setCustomMapStyleWithWebData:[self getMapData]];

  return self.mapView;
}
// 设置地图样式
- (NSData *)getMapData
{
  NSString *path = [NSString stringWithFormat:@"%@/gaodeMapStyle.data", [NSBundle mainBundle].bundlePath];
  NSData *data = [NSData dataWithContentsOfFile:path];
  return data;
}

- (void)viewDidLoad
{
  [super viewDidLoad];
  self.mapView.showsScale = _showScale;
  self.mapView.showsCompass = _compass;
  [self.mapView setCenterCoordinate:_centerCoordinate];
  [self.mapView setZoomLevel:_zoomLevel];
}

// 添加覆盖物
- (void)insertSubview:(WXComponent *)subcomponent atIndex:(NSInteger)index
{
  if ([subcomponent isKindOfClass:[DMapRenderer class]]) {
    DMapRenderer *overlayRenderer = (DMapRenderer *)subcomponent;
    [self addOverlay:overlayRenderer];
  }else if ([subcomponent isKindOfClass:[DMapViewMarkerComponent class]]) {
    [self addMarker:(DMapViewMarkerComponent *)subcomponent];
  }
}
// 更新属性
- (void)updateAttributes:(NSDictionary *)attributes
{
...
  if (attributes[@"zoom"]) {
    [self setZoomLevel:[attributes[@"zoom"] floatValue]];
  }
 ...
}
#pragma mark - component interface
- (void)setAPIKey:(NSString *)appKey
{
  [AMapServices sharedServices].apiKey = appKey;
}
- (void)setZoomLevel:(CGFloat)zoom
{
  [self.mapView setZoomLevel:zoom animated:YES];
}
#pragma mark - publish method
- (NSDictionary *)getUserLocation
{
  if(self.mapView.userLocation.updating && self.mapView.userLocation.location) {
    NSArray *coordinate = @[[NSNumber numberWithDouble:self.mapView.userLocation.location.coordinate.longitude],[NSNumber numberWithDouble:self.mapView.userLocation.location.coordinate.latitude]];
    NSDictionary *userDic = @{@"result":@"success",@"data":@{@"position":coordinate,@"title":@""}};
    return userDic;
  }
  return @{@"resuldt":@"false",@"data":@""};
}

#pragma mark - mapview delegate
/*!
 @brief 根据anntation生成对应的View
 */
- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
  if ([annotation isKindOfClass:[MAPointAnnotation class]])
  {
    MAPointAnnotation *pointAnnotation = (MAPointAnnotation *)annotation;
    if ([pointAnnotation.component isKindOfClass:[WXMapInfoWindowComponent class]]) {
      return [self _generateCustomInfoWindow:mapView viewForAnnotation:pointAnnotation];

    }else {
      return [self _generateAnnotationView:mapView viewForAnnotation:pointAnnotation];
    }
  }

  return nil;
}

/**
 * @brief 当选中一个annotation views时,调用此接口
 * @param mapView 地图View
 * @param view 选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
  MAPointAnnotation *annotation = view.annotation;
  for (WXComponent *component in self.subcomponents) {
    if ([component isKindOfClass:[WXMapViewMarkerComponent class]] &&
      [component.ref isEqualToString:annotation.component.ref]) {
      WXMapViewMarkerComponent *marker = (WXMapViewMarkerComponent *)component;
      if (marker.clickEvent) {
        [marker fireEvent:marker.clickEvent params:[NSDictionary dictionary]];
      }
    }
  }
}

/**
 * @brief 当取消选中一个annotation views时,调用此接口
 * @param mapView 地图View
 * @param view 取消选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view
{

}

/**
 * @brief 地图移动结束后调用此接口
 * @param mapView    地图view
 * @param wasUserAction 标识是否是用户动作
 */
- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction
{
  if (_isDragend) {
    [self fireEvent:@"dragend" params:[NSDictionary dictionary]];
  }
}

/**设置地图缩放级别 */
- (void)setMapViewRegion:(NSMutableArray *)poiArray animated:(BOOL)animated {
  NSMutableArray *arrays = [NSMutableArray array];
  for (MAPointAnnotation *anot in self.mapView.annotations) {
    CLLocationCoordinate2D coordinate = anot.coordinate;
    NSDictionary *poidic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:coordinate.latitude * 1000000], @"lat",
                [NSNumber numberWithInt:coordinate.longitude * 1000000], @"lng", nil];
    [arrays addObject:poidic];
  }

  MACoordinateRegion region = [self getCoordinateMapSpan:arrays];
  [self.mapView setRegion:region animated:animated];
}

/**配置地图region */
- (MACoordinateRegion)getCoordinateMapSpan:(NSMutableArray *)knightArray {
  MACoordinateRegion region;
  MACoordinateSpan span;

  CLLocationDegrees maxLat = -90;
  CLLocationDegrees maxLon = -180;
  CLLocationDegrees minLat = 90;
  CLLocationDegrees minLon = 180;

  if (knightArray && knightArray.count > 1) {
    for (int i = 0; i < knightArray.count; i++) {
      NSDictionary *knightDictionary = [knightArray objectAtIndex:i];
      float lat = [[knightDictionary objectForKey:@"lat"] floatValue] / 1000000;
      float lng = [[knightDictionary objectForKey:@"lng"] floatValue] / 1000000;

      if(lat > maxLat)
        maxLat = lat;
      if(lat < minLat)
        minLat = lat;
      if(lng > maxLon)
        maxLon = lng;
      if(lng < minLon)
        minLon = lng;
    }

    span.latitudeDelta = (maxLat - minLat) * 2 + 0.005;
    span.longitudeDelta = (maxLon - minLon) * 2 + 0.005;
    region.center.latitude = (maxLat + minLat) / 2;
    region.center.longitude = (maxLon + minLon) / 2;
    region.span = span;
  } else {
    NSDictionary *knightDictionary = [knightArray objectAtIndex:0];
    span.latitudeDelta = 0.01;
    span.longitudeDelta = 0.01;
    float lat = [[knightDictionary objectForKey:@"lat"] floatValue] / 1000000;
    float lng = [[knightDictionary objectForKey:@"lng"] floatValue] / 1000000;
    if (lat !=0 && lng != 0) {
      region.center.longitude = lng;
      region.center.latitude = lat;
    } else {
      region.center = [[ShopLocateManager shared] getLocationCoordinate];
    }
    region.span = span;
  }

  return region;
}
...
@end

2.2 weex-amap-marker

marker主要用于实现锚点,其效果如下:

要在Weex中自定义锚点,需要遵循以下几步:

  • 新建DMapViewMarkerComponent类继承WXComponent;
  • 在DMapViewComponent中使用mapview的addAnnotation方法添加DMapViewMarkerComponent组件;
  • 在DMapViewComponent重写insertSubview方法来添加子组建覆盖物。

部分实现代码如下:

- (instancetype)initWithRef:(NSString *)ref
            type:(NSString*)type
           styles:(nullable NSDictionary *)styles
         attributes:(nullable NSDictionary *)attributes
           events:(nullable NSArray *)events
        weexInstance:(WXSDKInstance *)weexInstance
{
  self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance];
  if (self) {
    if ([events containsObject:@"click"]) {
      _clickEvent = @"click";
    }
    NSArray *offset = attributes[@"offset"];
    if ([WXConvert isValidatedArray:offset]) {
      _offset = CGPointMake([WXConvert CGFloat:offset[0]],
                 [WXConvert CGFloat:offset[1]]);//[WXConvert sizeToWXPixelType:attributes[@"offset"] withInstance:self.weexInstance];
    }
    if (styles[@"zIndex"]) {
      _zIndex = [styles[@"zIndex"] integerValue];
    }
    _hideCallout = [[attributes map_safeObjectForKey:@"hideCallout"] boolValue];
    NSArray *position = [attributes map_safeObjectForKey:@"position"];
    if ([WXConvert isValidatedArray:position]) {
      _location = [attributes map_safeObjectForKey:@"position"];
    }
    _title = [attributes map_safeObjectForKey:@"title"];
    _icon = [attributes map_safeObjectForKey:@"icon"];
  }
  return self;
}

- (void)updateAttributes:(NSDictionary *)attributes
{
  DMapViewComponent *mapComponent = (DMapViewComponent *)self.supercomponent;
  if (attributes[@"title"]) {
    _title = attributes[@"title"];
    [mapComponent updateTitleMarker:self];
  }

  if ([attributes map_safeObjectForKey:@"icon"]) {
    _icon = attributes[@"icon"];
    [mapComponent updateIconMarker:self];
  }

  NSArray *position = [attributes map_safeObjectForKey:@"position"];
  if ([WXConvert isValidatedArray:position]) {
    _location = position;
    [mapComponent updateLocationMarker:self];
  }
}

weex-amap-info-window

weex-amap-info-window组件主要用于显示地图信息,如地图的图片模式,其效果如下:

要自定义窗体组件,需要用到以下几个步骤:

  • 新建DMapInfoWindowComponent类继承WXComponent;
  • 在DMapViewComponent中使用mapview的addAnnotation方法添加DMapInfoWindowComponent组件;
  • 在DMapViewComponent重写insertSubview方法来添加子组建信息窗体。

部分实现代码如下:

- (instancetype)initWithRef:(NSString *)ref
            type:(NSString*)type
           styles:(nullable NSDictionary *)styles
         attributes:(nullable NSDictionary *)attributes
           events:(nullable NSArray *)events
        weexInstance:(WXSDKInstance *)weexInstance
{
  self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance];
  if (self) {
    if (attributes[@"open"]) {
      _isOpen = [attributes[@"open"] boolValue];
    }

  }
  return self;
}

- (UIView *) loadView
{
  return [[DMapInfoWindow alloc] initWithAnnotation:_annotation reuseIdentifier:_identifier];
}

- (void)insertSubview:(WXComponent *)subcomponent atIndex:(NSInteger)index{}
- (void)updateAttributes:(NSDictionary *)attributes
{
  [super updateAttributes:attributes];
  if (attributes[@"open"])
  {
    _isOpen = [attributes[@"open"] boolValue];
    if (_isOpen) {
      [self _addSubView];
    }else {
      [self _removeViewFromSuperView];
    }
  }
}

#pragma mark - private method
 1. (void)_addSubView
{
  [self _removeViewFromSuperView];
  [(DMapViewComponent *)self.supercomponent addMarker:self];
}

 2. (void)_removeViewFromSuperView
{
  [(DMapViewComponent *)self.supercomponent removeMarker:self];
}

2.4 weex-amap-circle

weex-amap-circle组件主要用于实现画圈功能,如地图范围,其效果如下图所示:

  • 新建DMapCircleComponent类继承WXComponent;
  • 在DMapViewComponent中使用mapview的addOverlay方法添加DMapCircleComponent组件;
  • 在DMapViewComponent重写insertSubview方法来添加子组建圆。

下面是部分实现逻辑:

- (instancetype)initWithRef:(NSString *)ref
            type:(NSString*)type
           styles:(nullable NSDictionary *)styles
         attributes:(nullable NSDictionary *)attributes
           events:(nullable NSArray *)events
        weexInstance:(WXSDKInstance *)weexInstance
{
  self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance];
  if (self) {
    NSArray *centerArray = [attributes map_safeObjectForKey:@"center"];
    if ([WXConvert isValidatedArray:centerArray]) {
      _center = centerArray;
    }
    _radius = [[attributes map_safeObjectForKey:@"radius"] doubleValue];
  }
  return self;
}

- (void)updateAttributes:(NSDictionary *)attributes
{
  NSArray *centerArray = [attributes map_safeObjectForKey:@"center"];
  DMapViewComponent *parentComponent = (DMapViewComponent *)self.supercomponent;
  if ([WXConvert isValidatedArray:centerArray]) {
    _center = centerArray;
    [parentComponent removeOverlay:self];
    [parentComponent addOverlay:self];
  }else if ([[attributes map_safeObjectForKey:@"radius"] doubleValue] >= 0) {
    _radius = [[attributes map_safeObjectForKey:@"radius"] doubleValue];
    [parentComponent removeOverlay:self];
    [parentComponent addOverlay:self];
  }else {
    [super updateAttributes:attributes];
  }
}

2.5 weex-amap-polygon

weex-amap-polygon主要用于绘制多边形,其效果如下图:

要自定义weex-amap-polygon,可以从以下步骤着手:

  • 新建DMapPolygonComponent类继承WXComponent;
  • 在DMapViewComponent中使用mapview的addOverlay方法添加DMapPolygonComponent组件;
  • 在DMapViewComponent重写insertSubview方法来添加子组建多边形。

部分实现代码如下:

- (instancetype)initWithRef:(NSString *)ref
            type:(NSString*)type
           styles:(nullable NSDictionary *)styles
         attributes:(nullable NSDictionary *)attributes
           events:(nullable NSArray *)events
        weexInstance:(WXSDKInstance *)weexInstance
{
  self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance];
  if (self) {
    _fillColor = [attributes map_safeObjectForKey:@"fillColor"];
    _fillOpacity = [attributes map_safeObjectForKey:@"fillOpacity"];
  }
  return self;
}

- (void)updateAttributes:(NSDictionary *)attributes
{
  if ([attributes map_safeObjectForKey:@"fillColor"]) {
    _fillColor = [attributes map_safeObjectForKey:@"fillColor"];
  }else if ([attributes map_safeObjectForKey:@"fillOpacity"]) {
    _fillOpacity = [attributes map_safeObjectForKey:@"fillOpacity"];
  }else {
    [super updateAttributes:attributes];
  }
}

2.6 weex-amap-polyline

weex-amap-polyline组件主要用于在地图上实现划线操作,其最终效果如下图:

在iOS中,自定义直接需要从以下几步着手:

  1. 新建DMapPolylineComponent类继承WXComponent;
  2. 在DMapViewComponent中使用mapview的addOverlay方法添加DMapPolylineComponent组件;
  3. 在DMapViewComponent重写insertSubview方法来添加子组建折线。
@implementation DMapPolylineComponent

- (instancetype)initWithRef:(NSString *)ref
            type:(NSString*)type
           styles:(nullable NSDictionary *)styles
         attributes:(nullable NSDictionary *)attributes
           events:(nullable NSArray *)events
        weexInstance:(WXSDKInstance *)weexInstance
{
  self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance];
  if (self) {
    NSArray * pathArray = [attributes map_safeObjectForKey:@"path"];
    if ([WXConvert isValidatedArray:pathArray]) {
      _path = pathArray;
    }
    _strokeColor = [attributes map_safeObjectForKey:@"strokeColor"];
    _strokeWidth = [[attributes map_safeObjectForKey:@"strokeWidth"] doubleValue];
    _strokeOpacity = [[attributes map_safeObjectForKey:@"strokeOpacity"] doubleValue];
    _strokeStyle = [attributes map_safeObjectForKey:@"strokeStyle"];
  }
  _viewLoaded = NO;
  return self;
}

- (void)updateAttributes:(NSDictionary *)attributes
{
  NSArray * pathArray = [attributes map_safeObjectForKey:@"path"];
  DMapViewComponent *parentComponent = (DMapViewComponent *)self.supercomponent;
  if (pathArray) {
    if ([WXConvert isValidatedArray:pathArray]) {
      _path = pathArray;
    }
    [parentComponent removeOverlay:self];
    [parentComponent addOverlay:self];
    return;
  }else if ([attributes map_safeObjectForKey:@"strokeColor"]) {
    _strokeColor = [attributes map_safeObjectForKey:@"strokeColor"];
  }else if ([[attributes map_safeObjectForKey:@"strokeWidth"] doubleValue] >= 0) {
    _strokeWidth = [[attributes map_safeObjectForKey:@"strokeWidth"] doubleValue];
  }else if ([[attributes map_safeObjectForKey:@"strokeOpacity"] doubleValue] >= 0) {
    _strokeOpacity = [[attributes map_safeObjectForKey:@"strokeOpacity"] doubleValue];
  }else if ([attributes map_safeObjectForKey:@"strokeStyle"]) {
    _strokeStyle = [attributes map_safeObjectForKey:@"strokeStyle"];
  }
  [parentComponent updateOverlayAttributes:self];
}

@end

地图组件扩展

当然,我们也可以不使用weex-amap,而是直接使用高德地图进行扩展。

3.1 weex-amap

例如,我们自己扩展一个基于原生高德SDK生成的weex-amap组件。

要实现这么一个地图显示的功能,实现的步骤如下:

  • 新建DMapViewComponent类继承WXVContainer实现LocationSource;
  • 使用initComponentHostView(context)初始化;
  • 在DMapViewComponent实现文件中实现初始化map对象initMap,设置map的key;
  • @WXComponentProp注解实现属性绑定;
  • 通过fireEvent添加适当时机可以触发的事件;
  • 设置mapview的setInfoWindowAdapter,addPolyline,addPolygon,addCircle,addMarker等方式来实现覆盖物,,线,圆等等。

实现代码可以参考下面的代码:

 @Override
  protected FrameLayout initComponentHostView(@NonNull Context context) {
    mapContainer = new FrameLayout(context) {
      @Override
      public boolean onInterceptTouchEvent(MotionEvent ev) {
        // 解决与Scroller的滑动冲突
        if (ev.getAction() == MotionEvent.ACTION_UP) {
          requestDisallowInterceptTouchEvent(false);
        } else {
          requestDisallowInterceptTouchEvent(true);
        }
        return false;
      }
    };
    mapContainer.setBackgroundColor(fakeBackgroundColor);
    if (context instanceof Activity) {
      mActivity = (Activity) context;
    }

    return mapContainer;
  }

  @Override
  protected void setHostLayoutParams(FrameLayout host, int width, int height, int left, int right, int top, int bottom) {
    super.setHostLayoutParams(host, width, height, left, right, top, bottom);
    if (!isMapLoaded.get() && !isInited.get()) {
      isInited.set(true);
      mapContainer.postDelayed(new Runnable() {
        @Override
        public void run() {
          mMapView = new TextureMapView(getContext());
          mapContainer.addView(mMapView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
              ViewGroup.LayoutParams.MATCH_PARENT));
          WXLogUtils.e(TAG, "Create MapView " + mMapView.toString());
          initMap();
        }
      }, 0);
    }
  }

  private void initMap() {
    mMapView.onCreate(null);
    isMapLoaded.set(false);
    if (mAMap == null) {
      mAMap = mMapView.getMap();

      mAMap.setInfoWindowAdapter(new InfoWindowAdapter(this));
      mAMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
        @Override
        public void onMapLoaded() {
          WXLogUtils.e(TAG, "Map loaded");
          isMapLoaded.set(true);
          mZoomLevel = mAMap.getCameraPosition().zoom;
          mMapView.postDelayed(new Runnable() {
            @Override
            public void run() {
              execPaddingTasks();
            }
          }, 16);
        }
      });

      // 绑定 Marker 被点击事件
      mAMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
        // marker 对象被点击时回调的接口
        // 返回 true 则表示接口已响应事件,否则返回false
        @Override
        public boolean onMarkerClick(Marker marker) {

          if (marker != null) {
            for (int i = 0; i < getChildCount(); i++) {
              if (getChild(i) instanceof DMapMarkerComponent) {
                DMapMarkerComponent child = (DMapMarkerComponent) getChild(i);
                if (child.getMarker() != null && child.getMarker().getId() == marker.getId()) {
                  child.onClick();
                }
              }
            }
          }
          return false;
        }
      });
      mAMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {

        private boolean mZoomChanged;

        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
          mZoomChanged = mZoomLevel != cameraPosition.zoom;
          mZoomLevel = cameraPosition.zoom;
        }

        @Override
        public void onCameraChangeFinish(CameraPosition cameraPosition) {
          if (mZoomChanged) {

            float scale = mAMap.getScalePerPixel();
            float scaleInWeex = scale / WXViewUtils.getWeexPxByReal(scale);

            VisibleRegion visibleRegion = mAMap.getProjection().getVisibleRegion();
            WXLogUtils.d(TAG, "Visible region: " + visibleRegion.toString());
            Map<String, Object> region = new HashMap<>();
            region.put("northeast", convertLatLng(visibleRegion.latLngBounds.northeast));
            region.put("southwest", convertLatLng(visibleRegion.latLngBounds.southwest));

            Map<String, Object> data = new HashMap<>();
            data.put("targetCoordinate", cameraPosition.target.toString());
            data.put("zoom", cameraPosition.zoom);
            data.put("tilt", cameraPosition.tilt);
            data.put("bearing", cameraPosition.bearing);
            data.put("isAbroad", cameraPosition.isAbroad);
            data.put("scalePerPixel", scaleInWeex);
            data.put("visibleRegion", region);
            getInstance().fireEvent(getRef(), WeexConstant.EVENT.ZOOM_CHANGE, data);
          }
        }
      });

      mAMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
        boolean dragged = false;

        @Override
        public void onTouch(MotionEvent motionEvent) {

          switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_MOVE:
              dragged = true;
              break;
            case MotionEvent.ACTION_UP:
              if (dragged)
                getInstance().fireEvent(getRef(), WeexConstant.EVENT.DRAG_CHANGE);
              dragged = false;
              break;
          }
        }
      });
      setUpMap();
    }
  }
}

3.2 weex-amap-info-window

当然,我们也可以使用它实现weex-amap-info-window功能,虽然weex-amap-info-window已经被内置到weex-amap中。是的的思路如下:

新建DMapViewMarkerComponent类继承WXComponent;

在DMapViewComponent中使用mapview的addMarker方法添加DMapViewMarkerComponent组件 。

在DMapViewComponent中使用mapview的addMarker方法添加DMapViewMarkerComponent组件 。

private static class InfoWindowAdapter implements AMap.InfoWindowAdapter {

    private DMapViewComponent mWXMapViewComponent;

    InfoWindowAdapter(DMapViewComponent wxMapViewComponent) {
      mWXMapViewComponent = wxMapViewComponent;
    }

    @Override
    public View getInfoWindow(Marker marker) {
      return render(marker);
    }

    @Override
    public View getInfoContents(Marker marker) {
      return null;
//      return render(marker);
    }

    private View render(Marker marker) {
      WXMapInfoWindowComponent wxMapInfoWindowComponent = mWXMapViewComponent.mInfoWindowHashMap.get(marker.getId());
      if (wxMapInfoWindowComponent != null) {
        WXFrameLayout host = wxMapInfoWindowComponent.getHostView();
//        WXFrameLayout content = (WXFrameLayout) host.getChildAt(0);
        host.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
        host.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
        WXLogUtils.d(TAG, "Info size: " + host.getMeasuredWidth() + ", " + host.getMeasuredHeight());
        return host;
      } else {
        WXLogUtils.e(TAG, "WXMapInfoWindowComponent with marker id " + marker.getId() + " not found");
      }
      return null;
    }
  }

html5地图组件扩展

当然,我们可以使用对html5的amap进行扩展,例如扩展weex-amap。

4.1 weex-amap

示例代码如下:

<template>
  <div class="amap-page-container">
   <el-amap ref="map" vid="amapDemo" :amap-manager="amapManager" :center="center" :zoom="zoom" :plugin="plugin" :events="events" class="amap-demo">
   </el-amap>

   <div class="toolbar">
    <button @click="getMap()">get map</button>
   </div>
  </div>
 </template>

 <style>
  .amap-demo {
   height: 300px;
  }
 </style>

 <script>
  // NPM 方式
  // import { AMapManager } from 'vue-amap';
  // CDN 方式
  let amapManager = new VueAMap.AMapManager();
  module.exports = {
   data: function() {
    return {
     amapManager,
     zoom: 12,
     center: [121.59996, 31.197646],
     events: {
      init: (o) => {
       console.log(o.getCenter())
       console.log(this.$refs.map.$$getInstance())
       o.getCity(result => {
        console.log(result)
       })
      },
      'moveend': () => {
      },
      'zoomchange': () => {
      },
      'click': (e) => {
       alert('map clicked');
      }
     },
     plugin: ['ToolBar', {
      pName: 'MapType',
      defaultType: 0,
      events: {
       init(o) {
        console.log(o);
       }
      }
     }]
    };
   },

   methods: {
    getMap() {
     // amap vue component
     console.log(amapManager._componentMap);
     // gaode map instance
     console.log(amapManager._map);
    }
   }
  };
</script> 

4.2 weex-amap-marker

实现代码如下:

<template>
  <div class="amap-page-container">
   <el-amap vid="amapDemo" :zoom="zoom" :center="center" class="amap-demo">
    <el-amap-marker vid="component-marker" :position="componentMarker.position" :content-render="componentMarker.contentRender" ></el-amap-marker>
    <el-amap-marker v-for="(marker, index) in markers" :position="marker.position" :events="marker.events" :visible="marker.visible" :draggable="marker.draggable" :vid="index"></el-amap-marker>
   </el-amap>
   <div class="toolbar">
    <button type="button" name="button" v-on:click="toggleVisible">toggle first marker</button>
    <button type="button" name="button" v-on:click="changePosition">change position</button>
    <button type="button" name="button" v-on:click="chnageDraggle">change draggle</button>
    <button type="button" name="button" v-on:click="addMarker">add marker</button>
    <button type="button" name="button" v-on:click="removeMarker">remove marker</button>
   </div>
  </div>
 </template>

 <style>
  .amap-demo {
   height: 300px;
  }
 </style>

 <script>
  const exampleComponents = {
   props: ['text'],
   template: `<div>text from parent: {{text}}</div>`
  }
  module.exports = {
   name: 'amap-page',
   data() {
    return {
     count: 1,
     slotStyle: {
      padding: '2px 8px',
      background: '#eee',
      color: '#333',
      border: '1px solid #aaa'
     },
     zoom: 14,
     center: [121.5273285, 31.21515044],
     markers: [
      {
       position: [121.5273285, 31.21515044],
       events: {
        click: () => {
         alert('click marker');
        },
        dragend: (e) => {
         console.log('---event---: dragend')
         this.markers[0].position = [e.lnglat.lng, e.lnglat.lat];
        }
       },
       visible: true,
       draggable: false,
       template: '<span>1</span>',
      }
     ],
     renderMarker: {
      position: [121.5273285, 31.21715058],
      contentRender: (h, instance) => {
       // if use jsx you can write in this
       // return <div style={{background: '#80cbc4', whiteSpace: 'nowrap', border: 'solid #ddd 1px', color: '#f00'}} onClick={() => ...}>marker inner text</div>
       return h(
        'div',
        {
         style: {background: '#80cbc4', whiteSpace: 'nowrap', border: 'solid #ddd 1px', color: '#f00'},
         on: {
          click: () => {
           const position = this.renderMarker.position;
           this.renderMarker.position = [position[0] + 0.002, position[1] - 0.002];
          }
         }
        },
        ['marker inner text']
       )
      }
     },
     componentMarker: {
      position: [121.5273285, 31.21315058],
      contentRender: (h, instance) => h(exampleComponents,{style: {backgroundColor: '#fff'}, props: {text: 'father is here'}}, ['xxxxxxx'])
     },
     slotMarker: {
      position: [121.5073285, 31.21715058]
     }
    };
   },
   methods: {
    onClick() {
     this.count += 1;
    },
    changePosition() {
     let position = this.markers[0].position;
     this.markers[0].position = [position[0] + 0.002, position[1] - 0.002];
    },
    chnageDraggle() {
     let draggable = this.markers[0].draggable;
     this.markers[0].draggable = !draggable;
    },
    toggleVisible() {
     let visableVar = this.markers[0].visible;
     this.markers[0].visible = !visableVar;
    },
    addMarker() {
     let marker = {
      position: [121.5273285 + (Math.random() - 0.5) * 0.02, 31.21515044 + (Math.random() - 0.5) * 0.02]
     };
     this.markers.push(marker);
    },
    removeMarker() {
     if (!this.markers.length) return;
     this.markers.splice(this.markers.length - 1, 1);
    }
   }
  };
</script> 

4.3 weex-amap-info-window

<template>
  <div class="amap-page-container">
   <el-amap vid="amap" :zoom="zoom" :center="center" class="amap-demo">
    <el-amap-info-window
     :position="currentWindow.position"
     :content="currentWindow.content"
     :visible="currentWindow.visible"
     :events="currentWindow.events">
    </el-amap-info-window>
   </el-amap>
   <button @click="switchWindow(0)">Show First Window</button>
   <button @click="switchWindow(1)">Show Second Window</button>
  </div>
 </template>

 <style>
  .amap-demo {
   height: 300px;
  }
 </style>

 <script>
  module.exports = {
   data () {
    return {
     zoom: 14,
     center: [121.5273285, 31.21515044],
     windows: [
      {
       position: [121.5273285, 31.21515044],
       content: 'Hi! I am here!',
       visible: true,
       events: {
        close() {
         console.log('close infowindow1');
        }
       }
      }, {
       position: [121.5375285, 31.21515044],
       content: 'Hi! I am here too!',
       visible: true,
       events: {
        close() {
         console.log('close infowindow2');
        }
       }
      }
     ],
     slotWindow: {
      position: [121.5163285, 31.21515044]
     },
     currentWindow: {
      position: [0, 0],
      content: '',
      events: {},
      visible: false
     }
    }
   },

   mounted() {
    this.currentWindow = this.windows[0];
   },

   methods: {
    switchWindow(tab) {
     this.currentWindow.visible = false;
     this.$nextTick(() => {
      this.currentWindow = this.windows[tab];
      this.currentWindow.visible = true;
     });
    }
   }
  };
</script> 

API

当然,除了组件之外,我们还可以使用weex-amap的API来直接操作地图。

5.1 骑行路径Android实现

- (void)searchRidingRouteFromLat:(int)fromLat fromLng:(int)fromLng toLat:(int)toLat toLng:(int)toLng {

  AMapRidingRouteSearchRequest *request = [[AMapRidingRouteSearchRequest alloc] init];
  request.origin = [AMapGeoPoint locationWithLatitude:INT_2_FLOAT(fromLat) / 1000000
                       longitude:INT_2_FLOAT(fromLng) / 1000000];
  request.destination = [AMapGeoPoint locationWithLatitude:INT_2_FLOAT(toLat) / 1000000
                          longitude:INT_2_FLOAT(toLng) / 1000000];
  //发起路径搜索
  [self.aMapSearch AMapRidingRouteSearch:request];
}

- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response {
  if(response.route == nil) {
    return;
  }
  //通过AMapNavigationSearchResponse对象处理搜索结果
  AMapRoute *route = response.route;
  if (route.paths.count > 0) {
    AMapPath *amapPath = route.paths[0];
    NSArray *coordArray = amapPath.steps;
    NSMutableArray *mArray = [NSMutableArray array];
    NSArray *start = @[[NSString stringWithFormat:@"%f", request.origin.longitude], [NSString stringWithFormat:@"%f", request.origin.latitude]];
    [mArray insertObject:start atIndex:0];
    for (AMapStep *step in coordArray) {
      NSString *polistring = step.polyline;
      NSArray *array = [polistring componentsSeparatedByString:@";"];
      for (NSString *str in array) {
        NSArray *loc =[str componentsSeparatedByString:@","];
        [mArray addObject:loc];
      }
    }
    NSArray *end = @[[NSString stringWithFormat:@"%f", request.destination.longitude], [NSString stringWithFormat:@"%f", request.destination.latitude]];
    [mArray insertObject:end atIndex:mArray.count];
    [[DMessageChannelManager shared] postMessage:@"mapLines" andData:@{@"result": @"success", @"data": @{@"mapLines":mArray}}];
  }
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
  NSLog(@"Error: %@", error);
}

@end

5.2 骑行路径iOS实现

private RouteTask.OnRouteCalculateListener calculateListener = new RouteTask.OnRouteCalculateListener() {
    @Override
    public void onRouteCalculate(RideRouteResult result, int code) {
      HashMap<String, Object> res = new HashMap<>(2);
      if (code == 1000 && result != null) {
        Map<String, Object> data = new HashMap<>(1);
        data.put("mapLines", getLatLngList(result.getPaths().get(0), routeTask.getStartPoint(), routeTask.getEndPoint()));
        res.put("result", "success");
        res.put("data", data);
      } else {
        res.put("result", "fail");
      }
      String dataJson = new Gson().toJson(res);
      NotifyDataManager.getInstance().postMessage("mapLines", dataJson);
      WXLogUtils.d("RideRouteResult Json: " + dataJson);
    }
  };
     routeTask.addRouteCalculateListener(calculateListener);

  /**
   * 通过首尾经纬度计算走路规划路径中所有经纬度
   *
   * @param fromLat
   * @param fromLng
   * @param toLat
   * @param toLng
   */
  @JSMethod
  public void searchRidingRouteFromLat(float fromLat, float fromLng, float toLat, float toLng) {
    LocationEntity fromLe = new LocationEntity();
    fromLe.lat = fromLat / 1e6;
    fromLe.lng = fromLng / 1e6;
    LocationEntity toLe = new LocationEntity();
    toLe.lat = toLat / 1e6;
    toLe.lng = toLng / 1e6;
    if (routeTask == null) {
      routeTask = RouteTask.getInstance(mWXSDKInstance.getContext());
      routeTask.addRouteCalculateListener(calculateListener);
    }
    routeTask.search(fromLe, toLe);
  }

5.3 骑行路径Web实现

 let stream = weex.requireModule('stream')
  stream.fetch({
   timeout:20000,
   method: 'GET',
   url: 'https://restapi.amap.com/v4/direction/bicycling?key=87453539f02a65cd6585210fa2e64dc9&origin='+fromLng/1000000+','+fromLat/1000000+'&destination='+toLng/1000000+','+toLat/1000000,
 }, (response) => {
  if (response.status == 200) {
   let apiData = JSON.parse(response.data)

   if(apiData.data){
    var polyline= new Array();
    polyline[0] = apiData.data.origin.split(",");
    var polylineList = apiData.data.paths['0'].steps[0].polyline.split(";");

    for(var i=0;i<polylineList.length;i++) {
     var polylinePoint = polylineList[i].split(",");
     polyline.push(polylinePoint);
    }
    polyline.push(apiData.data.destination.split(",")); //字符分割
    callback({"result":"success","data": {"mapLines":polyline}});

   }
  }
 }, () => {})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 详解weex默认webpack.config.js改造

    本文介绍了weex默认webpack.config.js改造,分享给大家,具体如下: 解决的问题: 由于weex默认的webpack配置,会导致在src文件夹下的每一个.vue在temp文件夹下生成对应的一个.js文件,该js文件有一段这样的代码 contents += 'var App = require(\'' + relativePath + '\')\n'; contents += 'App.el = \'#root\'\n'; contents += 'new Vue(App)\n';

  • weex里Vuex state使用storage持久化详解

    在weex里使用Vuex作为state管理工具,问题来了,如何使得state可以持久化呢?weex官方提供store模块,因此我们可以尝试使用该模块来持久化state. 先看下该模块介绍: storage 是一个在前端比较常用的模块,可以对本地数据进行存储.修改.删除,并且该数据是永久保存的,除非手动清除或者代码清除.但是,storage 模块有一个限制就是浏览器端(H5)只能存储小于5M的数据,因为在 H5/Web 端的实现是采用 HTML5 LocalStorage API.而 Andro

  • Weex开发之WEEX-EROS开发踩坑(小结)

    随着Weex跨平台技术的持续火热,一时间涌现出了一大批基于Weex的开源解决方案,Weex Eros就是这么一个面向前端Vue的开源APP解决方案. 目前,如果直接使用Weex框架开发应用会存在很多痛点,诸如初始化启动的环境问题.项目工程化问题.版本升级与版本兼容问题和不支持增量更新等,而Weex Eros等开源解决方案能对上述问题进行有效的解决. Weex Eros的定位不是组件库,而是基于Weex封装的面向前端Vue的一整套APP开源解决方案,它关心的是整个APP项目.在Weex的强大支持下

  • 适合前端Vue开发童鞋的跨平台Weex的使用详解

    基于 Vue 技术栈的你如果需要选用一种移动端跨平台框架,是 Weex?React-Native?还是Flutter? 无疑,相对于后两者,因为你现在已有比较熟练的 Vue 基础,如果在其他条件一致的情况,Weex 无疑是最佳选择:但是 Weex 真的适合在实际项目中进行移动端跨平台开发吗?Weex 的开发效率.Weex 的质量是否满足需求? 一.开发环境 在这个 Weex app 开发中,我的开发环境相关配置如下: 工具名称 版本号 Node.js 8.2.1 Npm 5.3.0 Androi

  • 详解Weex基于Vue2.0开发模板搭建

    前言 最近有一些人反馈说在面试过程中常常被问到weex相关的知识,也侧面反映的weex的发展还是很可观的,可是目前weex的开发者大多数是中小型公司或者个人,大公司屈指可数,揪其原因可能是基于weex的开发正确的姿势大家并没有找到,而且市面上的好多轮子还是.we后缀的,众所周知,weex和vue一直在努力的进行生态互通,而且weex实现web标准化是早晚的问题,今天和大家分享一下weex基于vue2.0的开发框架模板~ 工作原理 先简单熟悉一下weex的工作原理,这里引用一下weex官网上的一直

  • 使用runtime 实现weex 跳转原生页面

    一.简述 最近项目组打算引入weex,并选定了一个页面进行试水.页面很简单,主要是获取数据渲染页面,并可以跳转到指定的页面.跟之前使用RN 相比,weex 确实要简单很多.从下图中我们可以看到,weex 页面需要跳转到原生页面,并且跳转到哪个页面我们可能并不能写死.也就是说只要原生页面之前项目中写过了,那么理论上来说使用weex 可以任意调用.那么问题来了,我原来的页面可能只知道名字,我怎么为那个页面传值呢?比如有个页面orderDetailVC  ,跳转时需要传入orderId,即orderD

  • IOS中Weex 加载 .xcassets 中的图片资源的实例详解

    IOS中Weex 加载 .xcassets 中的图片资源的实例详解 前言: 因为 .xcassets 中的图片资源只能通过 imageNamed: 方法加载,所以需要做一些特殊处理,才能提供给 Weex 使用(PS:纯属娱乐,因为 Weex 跨平台的特性,这种针对某一端做实现的方案实用价值并不大). 方案 观察 WeexSDK 发现有 WXImgLoaderProtocol 这个协议,这个协议包含了下面的方法: - (id<WXImageOperationProtocol>)downloadI

  • WEEX环境搭建与入门详解

    Weex简介 Weex 是阿里前端技术团队开源额一套跨平台开发方案,能以web的开发体验构建高性能.可扩展的 native 应用,Weex 的页面表示层使用 Vue ,并遵循 W3C 标准实现了统一的 JSEngine 和 DOM API,Weex和React Native一样是当前流行的跨平台开发框架.Weex的官方地址为:https://weex.apache.org/.Weex最简单的方法是使用 Playground App和在 dotWe 编写一个 Hello World 的例子,你甚至

  • weex slider实现滑动底部导航功能

    先看效果图 这里主要是使用了weex 的 slider 实现了可以滑动的底部导航框架 这里最主要的几个方法,如果光是看weex的官方文档,可能很痛苦,因为有一些功能虽然代码里已经写好,但是他并没有写出来,希望官方的文档能够尽快的完善起来 实现这样的功能,首先是一个slider的用法,这个官方文档是用这个来给大家做轮播图的. 首先我们不能设置自动播放ok了(直接不复制就ok了) 第二我们需要能够捕获到滚动到哪一页的索引,这个值需要用来设置下面的当前tab(监听slider的change 方法) 第

  • Weex开发之地图篇的具体使用

    在移动应用开发中,地图是一个很重要的工具,基于地图的定位.导航等特点衍生出了很多著名的移动应用.在Weex开发中,如果要使用定位.导航和坐标计算等常见的地图功能,可以使用weex-amap插件. weex-amap是高德针对Weex开发的一款地图插件,在Eros开发中,Eros对weex-amap进行二次封装,以便让开发者更集成地图功能.和其他的插件一样,集成此插件需要在原生平台中进行集成. 本文介绍的是如何在iOS中集成weex-amap,以及它的一些核心功能.本文将要介绍的内容如下: 1.高

  • Vue开发高德地图应用的最佳实践

    目录 前言 异步加载 封装组件 使用组件 自定义界面最佳实践 总结 前言 之前做不过不少关于地图交互的产品系统,目前国内主流的地图应用 SDK 只有几家:高德.百度和腾讯.所以个人觉得在 PC 应用上高德地图开发相对好一些,至少体验起来没有很明显的坑.这篇文章算是总结下开发地图应用总结吧. 异步加载 因为使用 js sdk 应用,脚本文件本身体积很大,所以要注意下加载的白屏时间,解决用户体验问题,目前绝大部分产品应用都是 SPA 单页面应用系统,所以我封装一个异步加载的方法: const loa

  • Android开发小技巧篇之集合

    1.对于过多的控件,功能类似,数量又多的,可以用include方法.在实现应用中,可以把控件放入List集合中. private void initView() { // TODO Auto-generated method stub pwd1 = (EditText) findViewById(R.id.pwd_et_6_1); pwd2 = (EditText) findViewById(R.id.pwd_et_6_2); pwd3 = (EditText) findViewById(R.i

  • java开发Activiti进阶篇流程实例详解

    目录 1.流程实例 1.1 什么是流程实例 1.2 业务管理 1.3 流程实例的挂起和激活 1.3.1 全部流程挂起 1.3.2 单个实例挂起 1.流程实例 1.1 什么是流程实例 流程实例(ProcessInstance)代表流程定义的执行实例 一个流程实例包括了所有的运行节点,我们可以利用这个对象来了解当前流程实例的进度等信息 例如:用户或者程序安装流程定义的内容发起了一个流程,这个就是一个流程实例 1.2 业务管理 ​流程定义部署在Activiti后,我们就可以在系统中通过Activiti

  • iOS开发系列--地图与定位源代码详解

    概览 现在很多社交.电商.团购应用都引入了地图和定位功能,似乎地图功能不再是地图应用和导航应用所特有的.的确,有了地图和定位功能确实让我们的生活更加丰富多彩,极大的改变了我们的生活方式.例如你到了一个陌生的地方想要查找附近的酒店.超市等就可以打开软件搜索周边;类似的,还有很多团购软件可以根据你所在的位置自动为你推荐某些商品.总之,目前地图和定位功能已经大量引入到应用开发中.今天就和大家一起看一下iOS如何进行地图和定位开发. 定位 地图 定位 要实现地图.导航功能,往往需要先熟悉定位功能,在iO

  • 微信小程序购物商城系统开发系列-工具篇的介绍

    微信小程序开放公测以来,一夜之间在各种技术社区中就火起来啦.对于它 估计大家都不陌生了,对于它未来的价值就不再赘述,简单一句话:可以把小程序简单理解为一个新的操作系统.新的生态,未来大部分应用场景都将给予微信小程序进行研发.基于对它的敬畏以及便于大家快速上手,特整理微信小程序商城开发系列,未来将持续增加微信小程序技术文章,让大家可全面了解如何快速开发微信小程序商城. 本篇文章主要介绍微信小程序官方提供的开发工具,俗话说:欲工善其身,必先利其器. 小程序开发文档地址https://mp.weixi

  • 高性能WEB开发 图片压缩篇

    一.缩小图片大小 当图片很多的时候,减少图片大小是提高下载速度最直接的方法. 1. 使用PNG8代替GIF(非动画图片),因为PNG8在效果一样的情况,图片大小比GIF要小. 2. 用fireworks处理PNG图片,在我们产品中很多PNG图片是美工直接用photoshop导出的, 后来让美工用fireworks处理PNG(大概的方式是选择保存为PNG8,删除背景色). 处理后100K的图片大小基本减少了3/4,但图片质量也会有少许降低,要看自己是否能接受. 3. 使用Smush.it(http

  • Angular2开发——组件规划篇

    本文集中讲讲笔者目前使用ng2来开发项目时对其组件的使用的个人的一些拙劣的经验. 先简单讲讲从ng1到ng2框架下组件的职责与地位: ng1中的一大特色--指令,分为属性型.标签型.css类型和注释型.其中写在css类以及注释中的组件想必多数人都不会去使用,而属性型指令与标签型指令则是ng1火遍宇宙的功臣之一.在ng2中,标签型指令干脆被分离出来,追随vue等新兴势力的风格升级并称为组件,并用来处理所有与视图(DOM)打交道的事情,包括展示数据与动画.而属性型指令则用于完善组件的功能,比如接收用

  • JavaWeb开发入门第二篇Tomcat服务器配置讲解

    一.Tomcat服务器端口的配置 Tomcat的所有配置都放在conf文件夹之中,里面的server.xml文件是配置的核心文件. 如果想修改Tomcat服务器的启动端口,则可以在server.xml配置文件中的Connector节点进行的端口修改 例如:将Tomcat服务器的启动端口由默认的8080改成8081端口 Tomcat服务器启动端口默认配置 <Connector port="8080" protocol="HTTP/1.1" connectionT

  • JavaWeb开发入门第一篇必备知识讲解

    一.基本概念 1.1.WEB开发的相关知识 WEB,在英语中web即表示网页的意思,它用于表示Internet主机上供外界访问的资源. Internet上供外界访问的Web资源分为: 1).静态web资源(如html 页面):指web页面中供人们浏览的数据始终是不变. 2).动态web资源:指web页面中供人们浏览的数据是由程序产生的,不同时间点访问web页面看到的内容各不相同. 静态web资源开发技术:Html 常用动态web资源开发技术:JSP/Servlet.ASP.PHP等 在Java中

随机推荐