2017-01-09 86 views
-5

首先,当我设置区域地图视图时,放大和缩小工作正常。当我尝试使用自定义视图设置注释时,以及设置注释时,缩放不起作用。用户放大后,会自动缩小。MKMapview在swift中无法正常工作

见下面我的代码:

 func setRegion(){ 
     var newRegion = MKCoordinateRegion() 
     //  let str = String(format: "%.01f", maxLoc) 
     //  maxdist = Double(str)! 
     let subscriberData = (SubscriberConfigDBHandler.SubConfigDBSharedInstance).getSubscriberUserDetails() 

     let latLanCoords :CLLocation = CLLocation(latitude:subscriberData.busLat as Double , longitude:subscriberData.busLng as Double) 
     newRegion.center.latitude = latLanCoords.coordinate.latitude 
     newRegion.center.longitude = latLanCoords.coordinate.longitude 
     newRegion.span.latitudeDelta = 0.075 
     newRegion.span.longitudeDelta = 0.075 
     self.liveTrackingMapView.setRegion(newRegion, animated: false) 

    } 

    private var mapChangedFromUserInteraction = false 

    private func mapViewRegionDidChangeFromUserInteraction() -> Bool { 
     let view = self.liveTrackingMapView.subviews[0] 
     if let gestureRecognizers = view.gestureRecognizers { 
      for recognizer in gestureRecognizers { 
       if(recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended) { 
        return true 
       } 
      } 
     } 
     return false 
    } 

    func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) { 
     mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction() 

    } 

    func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) { 
     if (mapChangedFromUserInteraction) { 

     } 
    } 
    func tapGesture(sender :UITapGestureRecognizer) { 
     if sender != tap1 { 
      self.searchListTableView .removeFromSuperview() 
     } 
    } 
    func navigationButtonTapped() { 
     for controller in self.navigationController!.viewControllers as Array { 
      if controller.isKindOfClass(DashBoardViewController) { 
       self.navigationController?.popToViewController(controller as UIViewController, animated: false) 
      } 
     } 
    } 
    func getLiveLocationData() { 
     self.timer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: #selector(getRefreshedLocationData), userInfo: nil, repeats: true) 

    } 
    func getRefreshedLocationData(){ 
     self.isFrom = "liveTracking" 
     if vehicleMap.count > 0 { 
      (SubscriberLocationService.sharedSubLocationService).sublocationDelegate = self 
      (SubscriberLocationService.sharedSubLocationService).syncLastLocationForSub(carrierIds as String, numberMap: numberMap, vehicleMap: vehicleMap, personMap: personMap, routeMap: routeMap, timeMap: timeMap, selCarrier: selectedId as String, lastTime: lastLocTime) 
      //   if (selectedId.intValue) > 0{ 
      //    selCarLocList = (SubscriberLocationService.sharedSubLocationService).getLocSetForSelectedCarrier(selectedId as String, lastLocTime: lastLocTime) 
      //       } 
      //   else{ 
      //    (SubscriberLocationService.sharedSubLocationService).syncLastLocationForSubDetails(timeMap) 
      //    (SubscriberLocationService.sharedSubLocationService).sublocationDelegate = self 
      //   } 
     } 
    } 

    //subscriberlocser delegate method 
    func getSubsriberLiveLocation() { 
     (ShowLoader.showLoaderSharedInstance).hideLoadingHUD() 
     initializeMapData() 
    } 

    func initializeMapData(){ 
     // (ShowToast.showToastSharedInstance).showActivityWithMessage() 
     let subscriberData = (PMLAppCache.sharedPMLCache).getSubscriberConfig() 
     isSchool = ((GlobalConstants.ORGANIZATION_TYPE_SchoolBus == subscriberData.organizationType) || (GlobalConstants.ORGANIZATION_TYPE_OfficeBus == subscriberData.organizationType) || (GlobalConstants.ORGANIZATION_TYPE_Taxi == subscriberData.organizationType)) 
     isOffice = ((GlobalConstants.ORGANIZATION_TYPE_SchoolBus == subscriberData.organizationType) || (GlobalConstants.ORGANIZATION_TYPE_OfficeBus == subscriberData.organizationType) || (GlobalConstants.ORGANIZATION_TYPE_Taxi == subscriberData.organizationType)) 
     isTaxi = ((GlobalConstants.ORGANIZATION_TYPE_SchoolBus == subscriberData.organizationType) || (GlobalConstants.ORGANIZATION_TYPE_OfficeBus == subscriberData.organizationType) || (GlobalConstants.ORGANIZATION_TYPE_Taxi == subscriberData.organizationType)) 
     // InitializeActivityAsyncTask().execute(); 

      self.getInitialData() 


    } 
     func getInitialData() { 
     self.locList.removeAllObjects() 
     var data : SubscriberLocationDetails = SubscriberLocationDetails() 
     carrierIdList = (CodeTypeCodeValueService.sharedcodeTypecodeValService).getAllIdFromAppDB(CodeTypeConstants.CARRIER_CODES) as! NSArray 
     carrierIds = "" 
     for i in 0 ..< carrierIdList.count{ 
      if i == carrierIdList.count-1 { 
       carrierIds.appendString(carrierIdList[i] as! String) 
      }else if i != 0{ 
       carrierIds.appendString(carrierIdList[i] as! String) 
       carrierIds.appendString(",") 
      } 
     } 
     locList = (SubscriberLocationService.sharedSubLocationService).getLastLocDataForCarriers() as! NSMutableArray 
     (SubscriberLocationService.sharedSubLocationService).sublocationDelegate = self 
     let sortDiscripter = NSSortDescriptor(key:"vehicleDesc", ascending: true) 
     let sortedResults: NSArray = locList.sortedArrayUsingDescriptors([sortDiscripter]) 
     locList.removeAllObjects() 
     locList = sortedResults.mutableCopy() as! NSMutableArray 


     for i in 0 ..< locList.count{ 

      data = locList[i] as! SubscriberLocationDetails 
      key = data.carrierId! 
      numberMap.setObject(data.personPhone!, forKey: key) 
      vehicleMap.setObject(data.vehicleDesc!, forKey: key) 
      personMap.setObject(data.personDesc!, forKey: key) 
      routeMap.setObject(data.routeNumber!, forKey: key) 
      if i == 0 { 
       timeMap.setObject(data.createdTime!, forKey: data.carrierId!) 
      }else if(timeMap.objectForKey(data.carrierId!) !== NSNull() && ((data.createdTime?.longLongValue > timeMap.objectForKey(data.carrierId!)?.longLongValue))){ 
       timeMap.setObject(data.createdTime!, forKey: data.carrierId!) 
      } 
      if ((lastLocTime.isEqualToNumber(0)) || (lastLocTime.longLongValue < data.createdTime?.longLongValue)) { 
       lastLocTime = data.createdTime! 
      } 

     } 
     if isSchool { 
      let sortDiscripter = NSSortDescriptor(key:"vehicleDesc", ascending: true) 
      let sortedResults: NSArray = locList.sortedArrayUsingDescriptors([sortDiscripter]) 
      locList.removeAllObjects() 
      locList = sortedResults.mutableCopy() as! NSMutableArray 

     }else{ 
      let sortDiscripter = NSSortDescriptor(key:"personDesc", ascending: true) 
      let sortedResults: NSArray = locList.sortedArrayUsingDescriptors([sortDiscripter]) 
      locList.removeAllObjects() 
      locList = sortedResults.mutableCopy() as! NSMutableArray 

     } 
     if selectedId .intValue > 0 { 
      for i in 0 ..< locList.count { 
       let locData = locList[i] as! SubscriberLocationDetails 
       if (locData.carrierId == selectedId) { 
        let latLanCoords :CLLocation = CLLocation(latitude:locData.latitude as! Double , longitude:locData.longitude as! Double) 
        self.centerMapOnLocation(latLanCoords) 
        self.setSingleAnnotation(locData) 
        setButtonsForScrollview(locData.carrierId!) 
       } 
      } 
     }else{ 
      setTheAnnotations(locList) 
      self.setButtonsForScrollview("") 
     } 

    } 



    // 115.315482669664 
    // -175.179858047742 
    // 133.003988043541 
    // 133.168361358532 
    // 8.32069131099509 
    // 133.089068653276 
    // -21.9573563525713 
    /*------- set Annotations **/ 
    func setTheAnnotations(annotArray : NSArray) { 
//  dispatch_async(dispatch_get_main_queue()) { 
      self.selectedId = "" 
      self.degreeMap.removeAllObjects() 
      //var oldLoc = CLLocation() 
      var newLoc = CLLocation() 
      //  let str = String(format: "%.01f", maxLoc) 
      //  maxdist = Double(str)! 
         for annotation in self.liveTrackingMapView.annotations as [MKAnnotation] { 
       self.liveTrackingMapView.removeAnnotation(annotation) 
      } 
//  print(annotArray.count) 
      for i in 0 ..< annotArray.count{ 
       let subLocData = annotArray[i] as! SubscriberLocationDetails 
       let initialLocation :CLLocation = CLLocation(latitude:subLocData.latitude as! Double , longitude:subLocData.longitude as! Double) 
       // let distanceInMeters = userloc.distanceFromLocation(initialLocation) 
       //if distanceInMeters > 0 { 
       let subConfig = (SubscriberConfigDBHandler.SubConfigDBSharedInstance).getSubscriberUserDetails() 

       let subscriberLocation = CLLocation(latitude: subConfig.busLat as Double , longitude : subConfig.busLng as Double) 
       newLoc = initialLocation 
       var locationArray = NSArray() 
       let placesData = NSUserDefaults.standardUserDefaults().objectForKey("myList") as? NSData 
       if let placesData = placesData { 
        locationArray = (NSKeyedUnarchiver.unarchiveObjectWithData(placesData) as? [SubscriberLocationDetails])! 
       } 
       self.key = subLocData.vehicleDesc! 
       if (UiUtils.uiUtilsSharedInstance).getUserDefaultsBool(GlobalConstants.FIRST_TIME_GET_BEARING){ 
        self.busDegree = self.getBearingBetweenTwoPoints1(subscriberLocation, point2: newLoc) 
        self.degreeMap.setObject(self.busDegree, forKey: self.key) 
        self.lastLocationArray.addObject(subLocData) 
        if i == self.locList.count - 1 { 
         (UiUtils.uiUtilsSharedInstance).updateUserDefaultsBool(GlobalConstants.FIRST_TIME_GET_BEARING, value: false) 

         let placesData1 = NSKeyedArchiver.archivedDataWithRootObject(self.lastLocationArray) 
         self.lastLocationArray.removeAllObjects() 
         NSUserDefaults.standardUserDefaults().setObject(placesData1, forKey: "myList") 
        } 
       }else{ 
        for i in 0 ..< locationArray.count{ 
         let locData = locationArray[i] as! SubscriberLocationDetails 
         if locData.carrierId == subLocData.carrierId { 
          let oldLocation = CLLocation(latitude:locData.latitude as! Double, longitude : locData.longitude as! Double) 
          self.busDegree = self.getBearingBetweenTwoPoints1(oldLocation, point2: newLoc) 
          self.degreeMap.setObject(self.busDegree, forKey: self.key) 
         } 
         if i == locationArray.count - 1 { 
          let placesData1 = NSKeyedArchiver.archivedDataWithRootObject(self.lastLocationArray) 
          self.lastLocationArray.removeAllObjects() 
          NSUserDefaults.standardUserDefaults().setObject(placesData1, forKey: "myList") 
         } 

        } 

       } 

       self.setAnnotationView(subLocData, coords: newLoc) 
      } 
//  } 
     //oldLoc = newLoc 
     //    let sourceIndex = oldLoc 
     //    let destinationIndex = newLoc 
     // 
     //    let c1 = sourceIndex.coordinate 
     //    let c2 = destinationIndex.coordinate 
     //    var a = [c1, c2] 
     //    let polyline = MKPolyline(coordinates: &a, count: a.count) 
     //    liveTrackingMapView.addOverlay(polyline) 



    } 

    func setAnnotationView(data : SubscriberLocationDetails ,coords :CLLocation) { 
     let locationCoords = CLLocationCoordinate2DMake(coords.coordinate.latitude, coords.coordinate.longitude) 
     pointAnnotation = CustomPointAnnotation(location: locationCoords) 
     if isSchool { 
      ImageNameStr = "school_bus_marker.png" 
     }else if isOffice{ 
      ImageNameStr = "office_bus_marker.png" 
     }else if isTaxi{ 
      ImageNameStr = "car_marker.png" 
     }else{ 
      ImageNameStr = "onfield_component_default.png" 
     } 

     pointAnnotation.coordinate = coords.coordinate 
     if personMap.valueForKey(data.carrierId!) as? String == "" { 
      pointAnnotation.title = "NA" 
     }else{ 
      pointAnnotation.title = personMap.valueForKey(data.carrierId!) as? String 
     } 
     pointAnnotation.subtitle = data.vehicleDesc 
     pinAnnotationView = MKPinAnnotationView(annotation: pointAnnotation, reuseIdentifier: reuseIdentifier) 
     self.liveTrackingMapView.addAnnotation(self.pinAnnotationView.annotation!) 
    } 
+0

你有没有仔细观察地图加载方法的语法和步骤..? –

+1

请包含一些代码。否则,我们基本上无法帮助你解决这个问题。 –

+0

我已经正确设置了区域,位置坐标和代表,但是当我尝试缩放到某个位置时,它会缩小。 – Jalindar

回答

0

您mapKit鉴于不断缩小的原因是,在下面的函数被调用,并保持“重置”您所在的区域。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     guard let location = locations.last as CLLocation? else { return } 

     let userCenter = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) 
     let region = MKCoordinateRegion(center: userCenter, span: MKCoordinateSpan(latitudeDelta: 180, longitudeDelta: 180)) 
     nameOfMapKitView.setRegion(region, animated: true) // THIS CAUSES MAP TO ZOOM OUT AGAIN 

} 

编辑:正如其他人所说,请张贴代码与你的问题,所以我们不必“猜测”的错误,幸运的是我遇到了这个其他的日子,所以我敢肯定这是什么您的地图视图有误。

+0

我不使用用户位置这就是为什么我不使用这种委托方法 – Jalindar

相关问题