如何在iOS中的驾驶模式下移除Google地图上的先前自定义标记 [英] How can i remove previous custom marker on Google Maps while Driving mode in iOS

查看:145
本文介绍了如何在iOS中的驾驶模式下移除Google地图上的先前自定义标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在开发一款应用程序,例如Taxi。



这里我在Google地图上添加了一些自定义标记(汽车图片)。问题是,当驾驶我的汽车符号不断添加上一个标记和更多的车方向是没有显示什么我正在通过道路。



这是我的代码:

  #pragma mark 
#pragma mark - showUserCurrentLocationDetails
- (void)showUserCurrentLocationDetails {

CLLocationCoordinate2D position = CLLocationCoordinate2DMake(LatValue,LongValue);
GMSMarker * location = [GMSMarker markerWithPosition:position];
UIImage * markerIcon = [UIImage imageNamed:@car-icon.png];
markerIcon = [markerIcon imageWithAlignmentRectInsets:UIEdgeInsetsMake(0,0,(markerIcon.size.height / 2),0)];
location.icon = markerIcon;
CLLocationDegrees degree = 90;
location.rotation = degrees;
location.groundAnchor = CGPointMake(0.5,0.5);
location.draggable = NO;
location.map = mapViewRef;
//要删除所有标记,请执行以下操作:
// [mapViewRef clear];
}

#pragma mark - startUserTracking
- (void)startUserTracking {

//收听GMSMapView的myLocation属性。
if(mapViewRef.observationInfo == nil){
[mapViewRef addObserver:self
forKeyPath:@myLocation
options:NSKeyValueObservingOptionNew
context:NULL];

//在地图添加到用户界面后询问我的位置数据。
dispatch_async(dispatch_get_main_queue(),^ {
mapViewRef.myLocationEnabled = YES;
});



$ b #pragma mark
#pragma mark - GMSMapViewDelegate
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {

CLLocation * location = [change objectForKey:NSKeyValueChangeNewKey ]。
mapViewRef.camera = [GMSCameraPosition cameraWithTarget:location.coordinate zoom:18];

LatValue = location.coordinate.latitude;
LongValue = location.coordinate.longitude;

driverLatitudeString = [[NSNumber numberWithFloat:LatValue] stringValue];

driverLongitudeString = [[NSNumber numberWithFloat:LongValue] stringValue];

//labelToShowCurrentRadiusValue.text = [NSString stringWithFormat:@%f,%f,location.coordinate.latitude,location.coordinate.longitude];
// NSLog(@Values is ::%f,%f,LatValue,LongValue);
[self sendDriverCurrentLocationDetailsToServer];
[self showUserCurrentLocationDetails];
}

你能帮我解决这个问题吗?
链接

将位置GMSMarker作为全局变量,并在获得新的位置坐标时更新其位置。

  @interface YourViewController()
{
GMSMarker * marker;
}
- (void)viewDidLoad
{
[super viewDidLoad];
$ b $ / *你的代码在这里也包括映射初始化。* /

//映射初始化后
marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(lat,lng);
marker.title = @您的位置;
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = myMapView;

$ b - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currLocation = [locations firstObject];

marker.position = CLLocationCoordinate2DMake(currLocation.latitude,currLocation.longitude);





$ b

对于旋转,我也面临同样的问题,因为它不旋转如预期。因此,我使用了UIImageView而不是GMSMarker,并更新了其中心,并根据之前和当前位置坐标之间的角度旋转它。

更多信息请查看< a href =https://stackoverflow.com/questions/35401873/move-and-rotate-gmsmarker-smoothly-along-last-updated-gps-coordinates-swift-ios/35401972#35401972>链接



或者这里是所需的代码:

  #importSampleViewController .h

#import< CoreLocation / CoreLocation.h>
#import< GoogleMaps / GoogleMaps.h>
#import< QuartzCore / QuartzCore.h>
#import< CoreMotion / CoreMotion.h>

@interface SampleViewController()< CLLocationManagerDelegate,GMSMapViewDelegate>
{
GMSMapView * myMapView;

CLLocationCoordinate2D previousSourcePoint;
CLLocation * prevCurrLocation,* currLocation;

// sample
UIImageView * sampleImgView;
}
@property CLLocationManager * locatnManager;

@end

@implementation SampleViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self){
//定制初始化
}
返回self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
//在从其笔尖加载视图后执行任何其他设置。

prevCurrLocation = [[CLLocation alloc] initWithLatitude:0.0 longitude:0.0];
// GMS MapView
GMSCameraPosition * camera = [GMSCameraPosition cameraWithLatitude:23.2500 longitude:77.4170 zoom:14.0];

CGRect mapRect;
// mapview的样本帧
if([UIScreen mainScreen] .bounds.size.height == 736)// iPhone 6 Plus 414 * 736
{
mapRect = CGRectMake (0,0,414,736-66);

else if([UIScreen mainScreen] .bounds.size.height == 667)// iphone 6 375 * 667
{
mapRect = CGRectMake(0,0, 375,667-66);

else if([UIScreen mainScreen] .bounds.size.height == 568)// iphone 5,5C,5S 320 * 568
{
mapRect = CGRectMake( 0,0,320,568-66);

else if([UIScreen mainScreen] .bounds.size.height == 480)// iphone 4,4S 320 * 480
{
mapRect = CGRectMake(0, 0,320,480-66);

else {
mapRect = CGRectMake(60,66,[UIScreen mainScreen] .bounds.size.width + 100,[UIScreen mainScreen] .bounds.size.height + 130);
}


myMapView = [GMSMapView mapWithFrame:mapRect camera:camera];
myMapView.myLocationEnabled = NO;
myMapView.delegate = self;
[myMapView.settings setAllGesturesEnabled:NO];
[myMapView.settings setZoomGestures:YES];
[myMapView.settings setScrollGestures:YES];


// Compass
myMapView.settings.compassButton = YES;
myMapView.padding = UIEdgeInsetsMake(40,0,0,0);
[myMapView setMinZoom:0.0 maxZoom:20.0];
用于(myMapView.gestureRecognizers中的id gestureRecognizer)
{
if(![gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
[
[myMapView removeGestureRecognizer:gestureRecognizer] ;
}
if(![gestureRecognizer isKindOfClass:[UIRotationGestureRecognizer class]])
{
[myMapView removeGestureRecognizer:gestureRecognizer];
}
}
[self.view addSubview:myMapView];


myMapView.frame = CGRectMake(0,0,[UIScreen mainScreen] .bounds.size.width,[UIScreen mainScreen] .bounds.size.height);

previousSourcePoint = CLLocationCoordinate2DMake(0.0,0.0);


sampleImgView = [[UIImageView alloc] init];
sampleImgView.center = myMapView.center;
sampleImgView.backgroundColor = [UIColor clearColor];
[myMapView addSubview:sampleImgView];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.8f];
sampleImgView.transform = CGAffineTransformMakeRotation(45);
[UIView commitAnimations];


[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3f];
sampleImgView.transform = CGAffineTransformMakeRotation(0);
[UIView commitAnimations];

CGPoint ImgCenter = sampleImgView.center;
CGRect frameRect = sampleImgView.frame;

frameRect.size.width = 20.0f;
frameRect.size.height = 30.0f;
sampleImgView.image = [UIImage imageNamed:@CAR]; //放置您自己的车辆图片

sampleImgView.center = ImgCenter;
sampleImgView.frame = frameRect; ([CLLocationManager headingAvailable]){
[self locationManager];



if

} else {
[[[UIAlertView alloc] initWithTitle:@Error
message:@设备不支持标题更新。
委托:无
cancelButtonTitle:@OK
otherButtonTitles:nil] show];


$ b #pragma mark - 上面是测试gms标记旋转
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.navigationController.navigationBarHidden = YES;

myMapView.settings.zoomGestures = YES;
}
- (void)viewDidUnload {
[super viewDidUnload];
@try {
[_locatnManager stopUpdatingLocation];
[self.locationManager stopUpdatingLocation];

@catch(NSException * exception){
}
@finally {
// Display Alternative
}
}

#pragma标记CLLocationManagerDelegate方法
- (CLLocationManager *)locationManager {
if(_locatnManager == nil){
_locatnManager = [[CLLocationManager alloc] init];
_locatnManager.desiredAccuracy = kCLLocationAccuracyBest;
_locatnManager.delegate = self;

//检查iOS 8.如果没有这个守卫,代码将在iOS 7的未知选择器上崩溃。
if([_locatnManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
[_locatnManager requestWhenInUseAuthorization];


//开始位置更新
if([CLLocationManager locationServicesEnabled]){
_locatnManager.distanceFilter = kCLDistanceFilterNone;
[_locatnManager startUpdatingLocation];
}
}

return _locatnManager;

$ b - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
currLocation = [locations firstObject];

CGPoint anglepoint = [myMapView.projection pointForCoordinate:currLocation.coordinate];
CGFloat angle = [self getAngle:anglepoint];
if(!isnan(angle)){
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.8f];
sampleImgView.transform = CGAffineTransformMakeRotation(angle);
[sampleImgView setCenter:[myMapView.projection pointForCoordinate:CLLocationCoordinate2DMake(currLocation.coordinate.latitude,currLocation.coordinate.longitude)]];
[UIView commitAnimations];
prevCurrLocation = currLocation;
}
else {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.8f];
[sampleImgView setCenter:[myMapView.projection pointForCoordinate:CLLocationCoordinate2DMake(currLocation.coordinate.latitude,currLocation.coordinate.longitude)]];
[UIView commitAnimations];
prevCurrLocation = currLocation;




- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([error code]!= kCLErrorLocationUnknown){
[self.locationManager stopUpdatingLocation];
self.locationManager.delegate = nil;


$ b - (CGFloat)getAngle:(CGPoint)touchedPoints
{
CGPoint previousLocationPoint = [myMapView.projection pointForCoordinate:prevCurrLocation.coordinate] ;

CGFloat x1 = previousLocationPoint.x;
CGFloat y1 = previousLocationPoint.y;

CGFloat x2 = touchedPoints.x;
CGFloat y2 = touchedPoints.y;

CGFloat x3 = x1;
CGFloat y3 = y2;

CGFloat oppSide = sqrtf(((x2-x3)*(x2-x3))+((y2-y3)*(y2-y3)));
CGFloat adjSide = sqrtf(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3)));

CGFloat angle = atanf(oppSide / adjSide);
//象限标识
if(x2

{
angle = 0-angle;
}


if(y2> previousLocationPoint.y)
{
angle = M_PI / 2 +(M_PI / 2 -angle);
}
返回角度;
}
$ b - (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position {
[sampleImgView setCenter:[myMapView.projection pointForCoordinate:CLLocationCoordinate2DMake(currLocation。 coordinate.latitude,currLocation.coordinate.longitude)]];
}

我对swift很陌生,但我已经设法获得所需的输出。 / p>

在Swift中:

 导入UIKit 
导入GoogleMaps
import Darwin

var locManager = CLLocationManager()
var prevCurrLocation = CLLocation()
var currLocation = CLLocation()
// sample
var sampleImgView = UIImageView();
var previousSourcePoint = CLLocationCoordinate2D()
let map = GMSMapView(frame:CGRect.zero)
let camera = GMSCameraPosition.camera(withLatitude:-33.86,longitude:151.20,zoom:18)


class ViewController:UIViewController,GMSMapViewDelegate,CLLocationManagerDelegate {


$ b覆盖func viewDidLoad(){
super.viewDidLoad )
//加载视图后,通常从一个笔尖执行任何其他设置。
}

重写func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
//处理任何可以重新创建的资源。
}

覆盖func loadView(){
//创建一个GMSCameraPosition,告诉地图显示

prevCurrLocation = CLLocation.init(纬度:0.0,经度:0.0)
previousSourcePoint = CLLocationCoordinate2DMake(0.0,0.0)

map.delegate = self
map.camera =相机
self.view =地图
map.isMyLocationEnabled = true
map.settings.myLocationButton = true

locManager = CLLocationManager()
locManager.delegate = self
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.startUpdatingLocation()

让image:UIImage = UIImage(命名为Bus)!
sampleImgView = UIImageView(image:image)
sampleImgView.center = map.center
sampleImgView.backgroundColor = UIColor.clear
map.addSubview(sampleImgView)

UIView.beginAnimations(nil,context:nil)
UIView.setAnimationDuration(0.3)
sampleImgView.transform = CGAffineTransform(rotationAngle:0)
UIView.commitAnimations()

让ImgCenter = CGPoint(x:sampleImgView.center.x,y:sampleImgView.center.y)
var frameRect = CGRect(origin:CGPoint(x:sampleImgView.frame.origin.x,y:sampleImgView .frame.origin.y),size:CGSize(width:sampleImgView.frame.size.width,height:sampleImgView.frame.size.height))

frameRect.size.width = 20.0
frameRect.size.height = 30.0



sampleImgView.center = ImgCenter;
sampleImgView.frame = frameRect;


$ b / * Google Maps委托方法* /
func mapView(mapView:GMSMapView,didTapInfoWindowOfMarker标记:GMSMarker){
print(infoWindowTapped )
}

func mapView(mapView:GMSMapView,didTapMarker marker:GMSMarker) - > Bool {
print(markerTapped)

返回true
}


/ *位置管理器委托* /
func locationManager(_ manager:CLLocationManager,didFailWithError error:Error){
manager.stopUpdatingLocation()
}

func locationManager(_ manager:CLLocationManager,didUpdateLocations locations:[CLLocation] ){

let userLocation:CLLocation = locations [0]
let long = userLocation.coordinate.longitude;
let lat = userLocation.coordinate.latitude;

currLocation = userLocation
print(locations = \(lat)\(long))

let anglepoint = map.projection.point(for :currLocation.coordinate)
让角度:CGFloat = getAngle(point:anglepoint)
if(!angle.isNaN)
{
UIView.beginAnimations(nil,context:nil)
UIView.setAnimationDuration(0.8)
sampleImgView.transform = CGAffineTransform(rotationAngle:angle)
sampleImgView.center = map.projection.point(for:currLocation.coordinate)
UIView。 commitAnimations()

prevCurrLocation = currLocation
}
else {

UIView.beginAnimations(nil,context:nil)
UIView.setAnimationDuration (0.8)
sampleImgView.center = map.projection.point(for:currLocation.coordinate)
UIView.commitAnimations()

prevCurrLocation = currLocation
}
}

func getAngle(point:CGPoint) - > CGFloat
{
let previousLocationPoint = map.projection.point(for:prevCurrLocation.coordinate)


让x1:Float = Float(previousLocationPoint.x)
让y1:Float = Float(previousLocationPoint.y)
让x2:Float = Float(point.x)
让y2:Float = Float(point.y)

让x3 = Float(x1)
let y3 = Float(y2)

let v1 =(x2-x3)*(x2-x3)
let v2 =(y2 (y1-y3)
让v3 = b $ b let oppSide = sqrtf(v1 + v2)
let adjSide = sqrtf(v3 + v4)

var angle = atanf(oppSide / adjSide);
//象限标识
if(x2< Float(previousLocationPoint.x))
{
angle = 0-angle;如果(y2> Float(previousLocationPoint.y))
{
angle = Float(M_PI)/ 2 +(Float(M_PI)/ 2) - 角度);

return CGFloat(angle)

$ b $ func mapView(mapView:GMSMapView,didChangeCameraPosition position:GMSCameraPosition){
sampleImgView.center = map。 projection.point(for:currLocation.coordinate)
}

希望这会有所帮助。


Currently I am working an app like Taxi.

Here I added some custom marker on Google maps(car image). The problem is while driving my car symbol is continuously added previous marker and more over car direction is not showing what ever I am going by road.

Here is my code:

#pragma mark
#pragma mark -- showUserCurrentLocationDetails
-(void)showUserCurrentLocationDetails{

  CLLocationCoordinate2D position =CLLocationCoordinate2DMake(LatValue,LongValue);
   GMSMarker *location = [GMSMarker markerWithPosition:position];
   UIImage *markerIcon = [UIImage imageNamed:@"car-icon.png"];
   markerIcon = [markerIcon imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, 0, (markerIcon.size.height/2), 0)];
    location.icon = markerIcon;
     CLLocationDegrees degrees = 90;
     location.rotation = degrees;
      location.groundAnchor = CGPointMake(0.5, 0.5);
       location.draggable = NO;
        location.map = mapViewRef;
       //To remove all markers simple do:
         //[mapViewRef clear];
    }

#pragma mark - startUserTracking
-(void)startUserTracking{

 // Listen to the myLocation property of GMSMapView.
 if (mapViewRef.observationInfo == nil){
    [mapViewRef addObserver:self
                 forKeyPath:@"myLocation"
                    options:NSKeyValueObservingOptionNew
                    context:NULL];

     // Ask for My Location data after the map has already been added to the UI.
     dispatch_async(dispatch_get_main_queue(), ^{
        mapViewRef.myLocationEnabled = YES;
      });
  }
}


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

   CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
   mapViewRef.camera = [GMSCameraPosition      cameraWithTarget:location.coordinate zoom:18];

   LatValue = location.coordinate.latitude;
   LongValue = location.coordinate.longitude;

   driverLatitudeString = [[NSNumber numberWithFloat:LatValue] stringValue];

   driverLongitudeString = [[NSNumber numberWithFloat:LongValue] stringValue];

   //labelToShowCurrentRadiusValue.text = [NSString stringWithFormat:@"%f , %f", location.coordinate.latitude, location.coordinate.longitude];
   //  NSLog(@"Values are :: %f ,%f",LatValue,LongValue);
   [self sendDriverCurrentLocationDetailsToServer];
   [self showUserCurrentLocationDetails];
}

Can you please help me out how can I overcome this issue? Link here

解决方案

In Objective-C: Take the location GMSMarker as global variable and update its position whenver you get new location coordinates.

    @interface YourViewController ()
    {
        GMSMarker *marker;
    }
    - (void)viewDidLoad
    {
        [super viewDidLoad];

         /*Your code here which includes map initialisation too.*/

         // After map initialisation
         marker = [[GMSMarker alloc] init];
         marker.position = CLLocationCoordinate2DMake(lat,lng);
         marker.title = @"Your location";
         marker.appearAnimation = kGMSMarkerAnimationPop;
         marker.map = myMapView;    
    }

   - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 
    {
        currLocation = [locations firstObject];

        marker.position = CLLocationCoordinate2DMake(currLocation.latitude,currLocation.longitude);
    }

For rotation, I've faced the same problem too, as its not rotating as expected. So I've took an UIImageView instead of GMSMarker and updating its center and rotating it according the angle between to previous and current location coordinates.

for more info please check this Link

Or here is the required code:

#import "SampleViewController.h"

#import <CoreLocation/CoreLocation.h>
#import <GoogleMaps/GoogleMaps.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreMotion/CoreMotion.h>

@interface SampleViewController ()<CLLocationManagerDelegate,GMSMapViewDelegate>
{
    GMSMapView *myMapView;        

    CLLocationCoordinate2D previousSourcePoint;        
    CLLocation *prevCurrLocation, *currLocation;

    //sample
    UIImageView *sampleImgView;
}
@property CLLocationManager *locatnManager;

@end

@implementation SampleViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    prevCurrLocation = [[CLLocation alloc]initWithLatitude:0.0 longitude:0.0];
     //GMS MapView
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:23.2500 longitude:77.4170 zoom:14.0];

    CGRect mapRect;
    //sample frames of mapview
    if ([UIScreen mainScreen].bounds.size.height==736)// iPhone 6 Plus  414*736
    {
        mapRect = CGRectMake(0, 0, 414, 736-66);
    }
    else if ([UIScreen mainScreen].bounds.size.height==667)// iphone 6  375*667
    {
        mapRect = CGRectMake(0, 0, 375, 667-66);
    }
    else if ([UIScreen mainScreen].bounds.size.height==568)//  iphone 5, 5C, 5S  320*568
    {
        mapRect = CGRectMake(0, 0, 320, 568-66);
    }
    else if ([UIScreen mainScreen].bounds.size.height==480)  //  iphone 4, 4S  320*480
    {
        mapRect = CGRectMake(0, 0, 320, 480-66);
    }
    else{
        mapRect = CGRectMake(60, 66, [UIScreen mainScreen].bounds.size.width + 100, [UIScreen mainScreen].bounds.size.height + 130);
    }


    myMapView = [GMSMapView mapWithFrame:mapRect camera:camera];
    myMapView.myLocationEnabled = NO;
    myMapView.delegate = self;
    [myMapView.settings setAllGesturesEnabled:NO];
    [myMapView.settings setZoomGestures:YES];
    [myMapView.settings setScrollGestures:YES];


    //Compass
    myMapView.settings.compassButton = YES;
    myMapView.padding = UIEdgeInsetsMake (40, 0, 0, 0);
    [myMapView setMinZoom:0.0 maxZoom:20.0];
    for (id gestureRecognizer in myMapView.gestureRecognizers)
    {
        if (![gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
        {
            [myMapView removeGestureRecognizer:gestureRecognizer];
        }
        if (![gestureRecognizer isKindOfClass:[UIRotationGestureRecognizer class]])
        {
            [myMapView removeGestureRecognizer:gestureRecognizer];
        }
    }
    [self.view addSubview:myMapView];


    myMapView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);

    previousSourcePoint = CLLocationCoordinate2DMake(0.0, 0.0);


    sampleImgView = [[UIImageView alloc]init];
    sampleImgView.center = myMapView.center;
    sampleImgView.backgroundColor = [UIColor clearColor];
    [myMapView addSubview:sampleImgView];

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.8f];
    sampleImgView.transform = CGAffineTransformMakeRotation(45);
    [UIView commitAnimations];


    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3f];
    sampleImgView.transform = CGAffineTransformMakeRotation(0);
    [UIView commitAnimations];

    CGPoint ImgCenter = sampleImgView.center;
    CGRect frameRect = sampleImgView.frame;

    frameRect.size.width = 20.0f;
    frameRect.size.height = 30.0f;
    sampleImgView.image = [UIImage imageNamed:@"CAR"]; // place your own vehicle image

    sampleImgView.center = ImgCenter;
    sampleImgView.frame = frameRect;



    if ([CLLocationManager headingAvailable]) {
        [self locationManager];

    } else {
        [[[UIAlertView alloc] initWithTitle:@"Error"
                                    message:@"Device doesn't support heading updates."
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];
    }
}

#pragma mark - above are test gms marker rotation
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;

    myMapView.settings.zoomGestures = YES;
}
-(void)viewDidUnload{
    [super viewDidUnload];
    @try {
        [_locatnManager stopUpdatingLocation];
        [self.locationManager stopUpdatingLocation];
    }
    @catch (NSException *exception) {
    }
    @finally {
        //Display Alternative
    }
}

#pragma mark CLLocationManagerDelegate methods
-(CLLocationManager *)locationManager {
    if (_locatnManager == nil) {
        _locatnManager = [[CLLocationManager alloc] init];
        _locatnManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locatnManager.delegate = self;

        // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
        if ([_locatnManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_locatnManager requestWhenInUseAuthorization];
        }

        // Start the location updates
        if ([CLLocationManager locationServicesEnabled]) {
            _locatnManager.distanceFilter = kCLDistanceFilterNone;
            [_locatnManager startUpdatingLocation];
        }
    }

    return _locatnManager;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    currLocation = [locations firstObject];

    CGPoint anglepoint = [myMapView.projection pointForCoordinate:currLocation.coordinate];
    CGFloat angle = [self getAngle:anglepoint];
    if(!isnan(angle)){
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.8f];
        sampleImgView.transform = CGAffineTransformMakeRotation(angle);
        [sampleImgView setCenter:[myMapView.projection pointForCoordinate:CLLocationCoordinate2DMake(currLocation.coordinate.latitude, currLocation.coordinate.longitude)]];
        [UIView commitAnimations];
        prevCurrLocation = currLocation;
    }
    else{
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.8f];
        [sampleImgView setCenter:[myMapView.projection pointForCoordinate:CLLocationCoordinate2DMake(currLocation.coordinate.latitude, currLocation.coordinate.longitude)]];
        [UIView commitAnimations];
        prevCurrLocation = currLocation;
    }

}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] != kCLErrorLocationUnknown) {
        [self.locationManager stopUpdatingLocation];
        self.locationManager.delegate = nil;
    }
}

-(CGFloat) getAngle: (CGPoint) touchedPoints
{
    CGPoint previousLocationPoint = [myMapView.projection pointForCoordinate:prevCurrLocation.coordinate];

    CGFloat x1 = previousLocationPoint.x;
    CGFloat y1 = previousLocationPoint.y;

    CGFloat x2 = touchedPoints.x;
    CGFloat y2 = touchedPoints.y;

    CGFloat x3 = x1;
    CGFloat y3 = y2;

    CGFloat oppSide = sqrtf(((x2-x3)*(x2-x3)) + ((y2-y3)*(y2-y3)));
    CGFloat adjSide = sqrtf(((x1-x3)*(x1-x3)) + ((y1-y3)*(y1-y3)));

    CGFloat angle = atanf(oppSide/adjSide);
    // Quadrant Identifiaction
    if(x2 < previousLocationPoint.x)
    {
        angle = 0-angle;
    }


    if(y2 > previousLocationPoint.y)
    {
        angle = M_PI/2 + (M_PI/2 -angle);
    }
    return angle;
}

- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position{
    [sampleImgView setCenter:[myMapView.projection pointForCoordinate:CLLocationCoordinate2DMake(currLocation.coordinate.latitude, currLocation.coordinate.longitude)]];
}

I am new to swift but I've managed to get required output.

In Swift:

import UIKit
import GoogleMaps
import Darwin

var locManager = CLLocationManager()
var prevCurrLocation = CLLocation()
var currLocation = CLLocation()
//sample
var sampleImgView = UIImageView();
var previousSourcePoint = CLLocationCoordinate2D()
let map = GMSMapView(frame: CGRect.zero )
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude:151.20, zoom: 18)


class ViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func loadView() {
    // Create a GMSCameraPosition that tells the map to display the

    prevCurrLocation = CLLocation.init(latitude: 0.0, longitude: 0.0)
    previousSourcePoint = CLLocationCoordinate2DMake(0.0, 0.0)

    map.delegate = self
    map.camera = camera
    self.view = map
    map.isMyLocationEnabled = true
    map.settings.myLocationButton = true

    locManager = CLLocationManager()
    locManager.delegate = self
    locManager.desiredAccuracy = kCLLocationAccuracyBest
    locManager.startUpdatingLocation()

    let image : UIImage = UIImage(named:"Bus")!
    sampleImgView = UIImageView(image: image)
    sampleImgView.center = map.center
    sampleImgView.backgroundColor = UIColor.clear
    map.addSubview(sampleImgView)

    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationDuration(0.3)
    sampleImgView.transform = CGAffineTransform(rotationAngle: 0)
    UIView.commitAnimations()

    let ImgCenter = CGPoint(x:sampleImgView.center.x, y:sampleImgView.center.y)
    var frameRect = CGRect(origin: CGPoint(x:sampleImgView.frame.origin.x, y:sampleImgView.frame.origin.y), size: CGSize(width: sampleImgView.frame.size.width, height: sampleImgView.frame.size.height))

    frameRect.size.width = 20.0
    frameRect.size.height = 30.0



    sampleImgView.center = ImgCenter;
    sampleImgView.frame = frameRect;
}


    /*Google Maps Delegate Methods*/
    func mapView(mapView: GMSMapView, didTapInfoWindowOfMarker marker: GMSMarker) {
        print("infoWindowTapped")
    }

    func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool {
        print("markerTapped")

        return true
    }


    /*Location Manager Delegate*/
       func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    manager.stopUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation:CLLocation = locations[0]
    let long = userLocation.coordinate.longitude;
    let lat = userLocation.coordinate.latitude;

    currLocation = userLocation
    print("locations = \(lat) \(long)")

    let anglepoint = map.projection.point(for: currLocation.coordinate)
    let angle:CGFloat = getAngle(point: anglepoint)
    if(!angle.isNaN)
    {
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.8)
        sampleImgView.transform = CGAffineTransform(rotationAngle: angle)
        sampleImgView.center = map.projection.point(for: currLocation.coordinate)
        UIView.commitAnimations()

        prevCurrLocation = currLocation
    }
    else{

        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.8)
        sampleImgView.center = map.projection.point(for: currLocation.coordinate)
        UIView.commitAnimations()

        prevCurrLocation = currLocation
    }
}

func getAngle(point: CGPoint) -> CGFloat
{
    let previousLocationPoint = map.projection.point(for: prevCurrLocation.coordinate)


    let x1:Float = Float(previousLocationPoint.x)
    let y1:Float = Float(previousLocationPoint.y)
    let x2:Float = Float(point.x)
    let y2:Float = Float(point.y)

    let x3 = Float(x1)
    let y3 = Float(y2)

    let v1 = (x2-x3)*(x2-x3)
    let v2 = (y2-y3)*(y2-y3)
    let v3 = (x1-x3)*(x1-x3)
    let v4 = (y1-y3)*(y1-y3)

    let oppSide = sqrtf(v1 + v2)
    let adjSide = sqrtf(v3 + v4)

    var angle = atanf(oppSide/adjSide);
    // Quadrant Identifiaction
    if(x2 < Float(previousLocationPoint.x))
    {
        angle = 0-angle;
    }

    if(y2 > Float(previousLocationPoint.y))
    {
        angle = Float(M_PI)/2 + (Float(M_PI)/2 - angle);
    }
    return CGFloat(angle)
}

func mapView(mapView: GMSMapView, didChangeCameraPosition position: GMSCameraPosition) {
    sampleImgView.center = map.projection.point(for: currLocation.coordinate)
}

Hope this helps.

这篇关于如何在iOS中的驾驶模式下移除Google地图上的先前自定义标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆