点击事件查询当前位置

发布于 2024-12-11 20:26:15 字数 6346 浏览 0 评论 0原文

当我的地图应用程序启动时,我正在显示澳大利亚大陆。我有一个按钮,我想在其上设置当前位置的编码,并在按下按钮后放大到该位置。我正在获取当前纬度和经度并能够传入 Web 服务 url。我做了以下编码

   - (void)viewDidLoad 
  { 

//to set the australia region
CLLocationCoordinate2D AusLoc = {-19.048230,133.685730};
MKCoordinateSpan AusSpan = MKCoordinateSpanMake(45, 45);
MKCoordinateRegion AusRegion = MKCoordinateRegionMake(AusLoc, AusSpan);

mapView.region = AusRegion;




    locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation]; }

   - (void)locationManager:(CLLocationManager *)manager
 didUpdateToLocation:(CLLocation *)newLocation
       fromLocation:(CLLocation *)oldLocation
  {

if((fabs(newLocation.coordinate.latitude) > 0.001) || (fabs(newLocation.coordinate.longitude) > 0.001)) {
    NSLog(@"Got location %f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
    if (currentLocation != nil) {
        [currentLocation release];
    }
    currentLocation = newLocation;
    [currentLocation retain];
}
NSString *lati=[NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
NSString *longi=[NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];

}

在“搜索”按钮(网络服务调用)上

NSString *url = [NSString stringWithFormat:@"http://.....url...../hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];

更新了编码:

    - (IBAction) showAddress {

    if (locationManager.location == nil)
{
    NSLog(@"user location not found yet or service disabled/denied");
}
else
{



    // Change map region using span (degrees)...
    MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
    MKCoordinateRegion region = MKCoordinateRegionMake
    (locationManager.location.coordinate, span);
    [mapView setRegion:region animated:YES];
}

   }

当我设置 mapView.showUserLocation = YES;当地图应用程序启动时(即点击按钮之前),它会显示当前位置。我对之前的答案感到困惑。那么我应该在按钮单击事件下放置什么代码来显示当前位置,并建议在为单击事件提供编码后是否有任何更改以在 Web 服务 url 中传递当前的 Lati 和 longi。提前致谢

编辑:-

   - (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id   <MKAnnotation>) annotation
   {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]   initWithAnnotation:annotation reuseIdentifier:@""];
annView.pinColor = MKPinAnnotationColorGreen;
//annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
annView.enabled = YES;
annView.image = [UIImage imageNamed:@"flagg.png"];

UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
                action:@selector(showDetails:)
      forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = rightButton;    

NSLog(@"Created annotation at: %f %f",    ((CustomPlacemark*)annotation).coordinate.latitude, ((CustomPlacemark*)annotation).coordinate.longitude);

[annView addObserver:self
          forKeyPath:@"selected"
             options:NSKeyValueObservingOptionNew
             context:@"GMAP_ANNOTATION_SELECTED"];

[annView autorelease];

return annView;
  }

  //return nil;


    - (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context{

  NSString *action = (NSString*)context;

// We only want to zoom to location when the annotation is actaully selected. This   will trigger also for when it's deselected
if([[change valueForKey:@"new"] intValue] == 1 && [action   isEqualToString:@"GMAP_ANNOTATION_SELECTED"]) 
{
    if([((MKAnnotationView*) object).annotation isKindOfClass:[CustomPlacemark   class]])
    {
        CustomPlacemark *place = ((MKAnnotationView*) object).annotation;

        // Zoom into the location       
        [mapView setRegion:place.coordinateRegion animated:TRUE];
        NSLog(@"annotation selected: %f %f", ((MKAnnotationView*) object).annotation.coordinate.latitude, ((MKAnnotationView*) object).annotation.coordinate.longitude);
    }
    }
      }

在搜索按钮中(调用网络服务)

     CLLocationCoordinate2D location;
        //currentLocation = newLocation;

              float radius = [[arrayNo objectAtIndex:[pickerView   selectedRowInComponent:0]] floatValue];
    //NSURL *url = [[NSURL alloc] initWithString:@"http://www.hettich.com.au/hespdirectory/phpsqlsearch_genxml.php?lat=-33.853468&lng=150.94042160000004&radius=5"];

   NSString *url = [NSString   stringWithFormat:@"http://www.hettich.com.au/hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];
//NSLog(@"NSString *url");
NSLog(@"%@", url);
   NSURL *URL = [NSURL URLWithString:url];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
  [xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)

{       resultButton.userInteractionEnabled = YES;
          //    NSMutableArray* annotations = [[NSMutableArray alloc] init];

    for (int i = 0; i < [appDelegate.markers count]; i++)
{

    marker *aMarker = [appDelegate.markers objectAtIndex:i];
    location.latitude = [aMarker.lat floatValue];
    location.longitude =[aMarker.lng floatValue];
    AddressAnnotation *annob = [[AddressAnnotation alloc] initWithCoordinate:location];
    annob.title = aMarker.name;
    annob.subTitle = aMarker.address;
    [mapView addAnnotation:annob];
    [annob release];


    CLLocationCoordinate2D ausLoc = {location.latitude,location.longitude};         //for zoom in the showroom results region
    MKCoordinateSpan ausSpan = MKCoordinateSpanMake(0.108889, 0.169922);
    MKCoordinateRegion ausRegion = MKCoordinateRegionMake(ausLoc, ausSpan);
    NSLog(@"No Errors");
    mapView.region = ausRegion;



}


}

I am Showing Australia continent when my Map application launch. I have one button on which I want to set coding for current location and zoom in to that location after pressing butoon. I am getting current latitude & longitude and able to pass in Web-service url. I did following coding

   - (void)viewDidLoad 
  { 

//to set the australia region
CLLocationCoordinate2D AusLoc = {-19.048230,133.685730};
MKCoordinateSpan AusSpan = MKCoordinateSpanMake(45, 45);
MKCoordinateRegion AusRegion = MKCoordinateRegionMake(AusLoc, AusSpan);

mapView.region = AusRegion;




    locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation]; }

and

   - (void)locationManager:(CLLocationManager *)manager
 didUpdateToLocation:(CLLocation *)newLocation
       fromLocation:(CLLocation *)oldLocation
  {

if((fabs(newLocation.coordinate.latitude) > 0.001) || (fabs(newLocation.coordinate.longitude) > 0.001)) {
    NSLog(@"Got location %f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
    if (currentLocation != nil) {
        [currentLocation release];
    }
    currentLocation = newLocation;
    [currentLocation retain];
}
NSString *lati=[NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
NSString *longi=[NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];

}

on Search button(web service calling)

NSString *url = [NSString stringWithFormat:@"http://.....url...../hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];

Updated with coding:

    - (IBAction) showAddress {

    if (locationManager.location == nil)
{
    NSLog(@"user location not found yet or service disabled/denied");
}
else
{



    // Change map region using span (degrees)...
    MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
    MKCoordinateRegion region = MKCoordinateRegionMake
    (locationManager.location.coordinate, span);
    [mapView setRegion:region animated:YES];
}

   }

When I set mapView.showUserLocation = YES; it shows current location when map application launch that is before tapping button. I am confused with previous answer. So What code should I put under button click event to show current location and also suggest If there is any change to pass current Lati and longi in web service url after giving coding for click event. Thanks in advance

Edited:-

   - (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id   <MKAnnotation>) annotation
   {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]   initWithAnnotation:annotation reuseIdentifier:@""];
annView.pinColor = MKPinAnnotationColorGreen;
//annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
annView.enabled = YES;
annView.image = [UIImage imageNamed:@"flagg.png"];

UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
                action:@selector(showDetails:)
      forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = rightButton;    

NSLog(@"Created annotation at: %f %f",    ((CustomPlacemark*)annotation).coordinate.latitude, ((CustomPlacemark*)annotation).coordinate.longitude);

[annView addObserver:self
          forKeyPath:@"selected"
             options:NSKeyValueObservingOptionNew
             context:@"GMAP_ANNOTATION_SELECTED"];

[annView autorelease];

return annView;
  }

  //return nil;


    - (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context{

  NSString *action = (NSString*)context;

// We only want to zoom to location when the annotation is actaully selected. This   will trigger also for when it's deselected
if([[change valueForKey:@"new"] intValue] == 1 && [action   isEqualToString:@"GMAP_ANNOTATION_SELECTED"]) 
{
    if([((MKAnnotationView*) object).annotation isKindOfClass:[CustomPlacemark   class]])
    {
        CustomPlacemark *place = ((MKAnnotationView*) object).annotation;

        // Zoom into the location       
        [mapView setRegion:place.coordinateRegion animated:TRUE];
        NSLog(@"annotation selected: %f %f", ((MKAnnotationView*) object).annotation.coordinate.latitude, ((MKAnnotationView*) object).annotation.coordinate.longitude);
    }
    }
      }

In Search button(calling webservice)

     CLLocationCoordinate2D location;
        //currentLocation = newLocation;

              float radius = [[arrayNo objectAtIndex:[pickerView   selectedRowInComponent:0]] floatValue];
    //NSURL *url = [[NSURL alloc] initWithString:@"http://www.hettich.com.au/hespdirectory/phpsqlsearch_genxml.php?lat=-33.853468&lng=150.94042160000004&radius=5"];

   NSString *url = [NSString   stringWithFormat:@"http://www.hettich.com.au/hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];
//NSLog(@"NSString *url");
NSLog(@"%@", url);
   NSURL *URL = [NSURL URLWithString:url];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
  [xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)

{       resultButton.userInteractionEnabled = YES;
          //    NSMutableArray* annotations = [[NSMutableArray alloc] init];

    for (int i = 0; i < [appDelegate.markers count]; i++)
{

    marker *aMarker = [appDelegate.markers objectAtIndex:i];
    location.latitude = [aMarker.lat floatValue];
    location.longitude =[aMarker.lng floatValue];
    AddressAnnotation *annob = [[AddressAnnotation alloc] initWithCoordinate:location];
    annob.title = aMarker.name;
    annob.subTitle = aMarker.address;
    [mapView addAnnotation:annob];
    [annob release];


    CLLocationCoordinate2D ausLoc = {location.latitude,location.longitude};         //for zoom in the showroom results region
    MKCoordinateSpan ausSpan = MKCoordinateSpanMake(0.108889, 0.169922);
    MKCoordinateRegion ausRegion = MKCoordinateRegionMake(ausLoc, ausSpan);
    NSLog(@"No Errors");
    mapView.region = ausRegion;



}


}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最单纯的乌龟 2024-12-18 20:26:15

在点击按钮的方法中,您应该首先检查位置管理器是否已获取位置,然后将地图的中心或区域设置为用户的位置:

if (locationManager.location == nil)
{
    NSLog(@"user location not found yet or service disabled/denied");
}
else
{
    // Change map center (preserving current zoom level)...
    [mapView setCenterCoordinate:locationManager.location.coordinate animated:YES];

    // --OR--

    // Change map region using distance (meters)...
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance
                           (locationManager.location.coordinate, 1000, 1000);
    [mapView setRegion:region animated:YES];

    // --OR--

    // Change map region using span (degrees)...
    MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
    MKCoordinateRegion region = MKCoordinateRegionMake
                           (locationManager.location.coordinate, span);
    [mapView setRegion:region animated:YES];
}

didUpdateToLocation 方法中,您正在设置一个“currentLocation”变量,但我认为没有必要。 locationManager 已经有一个 location 属性。

无论如何,仅将大于 0.001 的绝对纬度或经度视为“有效”是不正确的,因为 a) 它排除了赤道或本初子午线附近的位置(即使您只对澳大利亚感兴趣,但这种逻辑是错误的方法) ,b) 最好检查 newLocation 本身是否为 nil

In your button tapped method, you should first check if the location manager has obtained a location and then set the map's center or region to the user's location:

if (locationManager.location == nil)
{
    NSLog(@"user location not found yet or service disabled/denied");
}
else
{
    // Change map center (preserving current zoom level)...
    [mapView setCenterCoordinate:locationManager.location.coordinate animated:YES];

    // --OR--

    // Change map region using distance (meters)...
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance
                           (locationManager.location.coordinate, 1000, 1000);
    [mapView setRegion:region animated:YES];

    // --OR--

    // Change map region using span (degrees)...
    MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
    MKCoordinateRegion region = MKCoordinateRegionMake
                           (locationManager.location.coordinate, span);
    [mapView setRegion:region animated:YES];
}

In the didUpdateToLocation method, you are setting a "currentLocation" variable but I don't see a need for it. The locationManager already has a location property.

In any case, only considering absolute latitudes or longitudes greater than 0.001 as "valid" is incorrect because a) it excludes locations near the equator or prime meridian (even though you're only interested in Australia this logic is the wrong way to go), and b) it's better instead to check if newLocation itself is nil.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文