Android GoogleMap定位集成彩民之家论坛9066777

2019-09-18 21:55 来源:未知

彩民之家论坛9066777 1Paste_Image.png彩民之家论坛9066777 2Paste_Image.png彩民之家论坛9066777 3Paste_Image.png

一开始一直崩溃

彩民之家论坛9066777 4

Paste_Image.png

彩民之家论坛9066777 5

Paste_Image.png

后来解决啦 没有添加谷歌地图的key

定位我用的系统的定位 CLLocationManager 这就不用多说啦把。(在国内有偏差,国外是正常的,因为火星坐标 (GCJ-02))

5DE97EEE-194D-4468-AA4C-CE8C54DFD3E3.png

使用时手机必须需要翻墙,安装Google play 商店、Google play service、Google play 框架,而且都必须是最新版本,这样才能够显示地图,但是还没有实现定位。

下面说几个代理方法 有些事百度的有些是自己试的,不对的话希望指出来。谢谢

/地图代理
- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture{
    NSLog(@"gesture === %@",[NSNumber numberWithBool:gesture]);
}

//这个代理方法主要作用就是当你移动镜头也就是拖动地推的时候,就会调用这个方法
- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position{
    NSLog(@"didChangeCameraPosition ==== %@",position);
}
//这个代理方法你就可以拿到屏幕中心点的位置的经纬度了,这是一个很简单的方法。当然,这个方法是有缺陷的,就是我们只能拿到经纬度,却拿不到经纬度所对应的地址之类的一些信息。
- (void)mapView:(GMSMapView *)mapView idleAtCameraPosition:(GMSCameraPosition *)position{

    NSLog(@"idleAtCameraPosition ==== %@",position);
    NSLog(@"target ==== %f,%f",position.target.latitude,position.target.longitude);

    //这个方法是清理掉地图上所有的东西,包括什么大头针之类的,这里的目的是为了使地图上只有一个大头针
//    [_mapView clear];
//    _marker = [[GMSMarker alloc] init];
//    _marker.position = CLLocationCoordinate2DMake(position.target.latitude, position.target.longitude);
//    _marker.icon = [UIImage imageNamed:@"bigLoc"];
//    _marker.map = _mapView;
}

//这个三个代理方法要怎么解释我就真不知道了,大家伙可以试试
//开始
- (void)mapViewDidStartTileRendering:(GMSMapView *)mapView{
//    NSLog(@"mapViewDidStartTileRendering ==== %@",mapView);
}
//滑动
- (void)mapViewDidFinishTileRendering:(GMSMapView *)mapView{
//    NSLog(@"mapViewDidFinishTileRendering ==== %@",mapView);
}
//暂停
- (void)mapViewSnapshotReady:(GMSMapView *)mapView{
//    NSLog(@"mapViewSnapshotReady ==== %@",mapView);
}

彩民之家论坛9066777 6

/** * GPS定位 */public class GPSFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, LocationListener { public static final int UPDATE_INTERVAL = 5000; public static final int FASTEST_UPDATE_INTNERVAL = 2000; public static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; private LocationRequest locationRequest; private GoogleMap mMap; private GoogleApiClient mGoogleApiClient; Location myLocation; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_g, container, false); if (mMap == null) { SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager() .findFragmentById; mapFragment.getMapAsync; } if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(getActivity .addConnectionCallbacks .addOnConnectionFailedListener .addApi(LocationServices.API) .build(); } locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(UPDATE_INTERVAL).setFastestInterval(FASTEST_UPDATE_INTNERVAL); LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Toast.makeText(getActivity(), "Please enable GPS!", Toast.LENGTH_LONG).show(); Intent intent = new Intent(Settings.ACTION_LOCALE_SETTINGS); startActivity; } return v; } public void connect() { if (mGoogleApiClient != null) { mGoogleApiClient.connect(); } } @Override public void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override public void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } @Override public void onMapReady(GoogleMap googleMap) { Log.e("onMapReady", ""); mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng; mMap.addMarker(new MarkerOptions().position.title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng; } @Override public void onConnected(Bundle bundle) { Log.e("", "onConnected"); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (myLocation != null) { Log.e("", "myLocation:"   myLocation); updateToNewLocation(myLocation); } startLocation(); } // 更新位置 private void updateToNewLocation(Location location) { Log.e("updateToNewLocation", ""); if (location != null) { double latitude = location.getLatitude(); double longitude = location.getLongitude(); Toast.makeText(getActivity(), "latitude:"   latitude   "nlongitude:"   longitude, Toast.LENGTH_SHORT).show(); if (mMap != null) { mMap.clear(); mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude.title("You are here")); } } else { Toast.makeText(getActivity(), "Unable to get geographic information", Toast.LENGTH_SHORT).show(); } }//开始定位 public void startLocation() { Log.e("", "startLocation mGoogleApiClient.isConnected():"   mGoogleApiClient.isConnected; if (mGoogleApiClient.isConnected { if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, locationRequest, this); } } @Override public void onConnectionSuspended { }//定位成功会回调onLocationChanged() @Override public void onLocationChanged(Location amapLocation) { Log.e("", "onLocationChanged"); if (amapLocation != null) { Log.e("", "onLocationChanged 定位成功,getLatitude:"   amapLocation.getLatitude()   ",getLongitude:"   amapLocation.getLongitude; updateToNewLocation(amapLocation); } else { Log.e("", "定位失败....."); } } @Override public void onConnectionFailed(ConnectionResult connectionResult) { if (connectionResult.hasResolution { try { connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); } } else { new AlertDialog.Builder(getActivity.setMessage("Connection failed.Error code:"   connectionResult.getErrorCode; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CONNECTION_FAILURE_RESOLUTION_REQUEST) { } }}

Google Maps接入 必须翻墙

接口文档

演示代码

开发者控制台

参考援助
集成很简单 跟着上面的网址一步一步做就可以

最后PS:plist 文件里面的设置
在 iOS9 中需要配置 plist 文件

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>googlechromes</string>
    <string>comgooglemaps</string>
</array>

彩民之家论坛9066777 7

彩民之家论坛9066777 8Paste_Image.png彩民之家论坛9066777 9Paste_Image.png

ps 也可以使用KVO定位

- (void)viewDidLoad {
    //...
    [self.mapView addObserver:self forKeyPath:"myLocation" options:0 context:nil];
}
- (void)dealloc {
    [_mapView removeObserver:self forKeyPath:@"myLocation"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if([keyPath isEqualToString:@"myLocation"]) {
        CLLocation *l = [object myLocation];
        //...
    }
}
![](https://upload-images.jianshu.io/upload_images/2599480-ea73af42b226fe97.png)

F1CA49B8-CF5A-47D3-A072-3BB24110E031.png

2.在创建项目时选择Google Maps Activity

下面开始粘代码

引入头文件

#import <GoogleMaps/GoogleMaps.h>

static NSString *const kAPIKey = @"你自己的key";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
//    [GMSServices provideAPIKey:@"AIzaSyAleSTvh3HFWKnUFgJStps-nxw3opQARaw"];
    if (kAPIKey.length == 0) {
        // Blow up if APIKey has not yet been set.
        NSString *bundleId = [[NSBundle mainBundle] bundleIdentifier];
        NSString *format = @"Configure APIKey inside SDKDemoAPIKey.h for your "
        @"bundle `%@`, see README.GoogleMapsDemos for more information";
        @throw [NSException exceptionWithName:@"DemoAppDelegate"
                                       reason:[NSString stringWithFormat:format, bundleId]
                                     userInfo:nil];
    }
    [GMSServices provideAPIKey:kAPIKey];
    return YES;
}

 //地图
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
                                                            longitude:151.2086
                                                                 zoom:12];

    _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    _mapView.delegate =self;
    _mapView.settings.compassButton = YES;
    _mapView.settings.myLocationButton = YES;


 //大头针
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(-33.86, 151.20);
    marker.title = @"Sydney";
    marker.snippet = @"Australia";
    marker.map = _mapView;

// 划线
    GMSMutablePath *path = [GMSMutablePath path];
    [path addCoordinate:CLLocationCoordinate2DMake(@(-33.860).doubleValue,@(151.208).doubleValue)];
    [path addCoordinate:CLLocationCoordinate2DMake(@(-33.860).doubleValue,@(151.008).doubleValue)];
    [path addCoordinate:CLLocationCoordinate2DMake(@(-33.860).doubleValue,@(150.508).doubleValue)];
    [path addCoordinate:CLLocationCoordinate2DMake(@(-32.860).doubleValue,@(150.208).doubleValue)];

    GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path];
    rectangle.strokeWidth = 2.f;
    rectangle.map = _mapView;
     self.view = _mapView;

彩民之家论坛9066777 10

要注意google_maps_api中对应的证书指纹和包名会在申请key时用到

前言:最近因为项目需求需要做国际版本,需要把国内的高德地图换成谷歌地图GoogleMaps 。网上一查,关于GoogleMaps的坑太多,资料太少,在此献上最近忙活的成果,提供集成GoogleMaps的一些方法。

前言:最近因为项目需求,需要集成GoogleMaps 。网上一查,关于GoogleMaps的坑太多,资料太少,在此献上最近忙活的成果,提供集成GoogleMaps的一些方法。
一开始我是按照《http://www.jianshu.com/p/dc7d267d63d0 》 里面提供的方法来集成。但是发现GoogleMaps已经升级到2.0.1 ,该文中的方法已经过时,因此走上了自力更生的道路

彩民之家论坛9066777 11Paste_Image.png

b.根据图中的地址直接复制黏贴到浏览器,下载GoogleMaps。这里也需要翻墙,但是不需要用VPN也可以。建议大家使用“Lantern”这款软件。一键翻墙。

彩民之家论坛9066777 12Paste_Image.png彩民之家论坛9066777 13Paste_Image.png

彩民之家论坛9066777 14

运行时可能会遇到一些问题,详细可参看 gradle中添加如下:

彩民之家论坛9066777 15

3.开始定位,详细代码如下:

B6E17C35-8E6E-49AC-AAE3-0AAD71B18547.png

之前项目中需要集成GoogleMap定位,真是走了不少弯路,才弄懂。GoogleMap地图详细集成步骤如下:1.首先引入依赖包

2.如果没有VPN(毕竟试用账号有限),这里提供给大家一种可用方案。
a.首先还是使用终端搜索GoogleMaps,如下图

彩民之家论坛9066777 16

最后,Google地图顺利出来 。有问题可以留言。

66BD22B9-8CE5-46E1-A01A-5EE7BE3F4FDD.png

Other Linker Flags

F6A3CAC4-FA14-475C-8D1C-6ADC671F21E5.png

彩民之家论坛9066777 17

接下来,点击Build Setting标签页,并寻找Other Linker Flags 设置。找到之后,将-ObjC赋值给它。

彩民之家论坛9066777 18

Paste_Image.png

彩民之家论坛9066777 19

  • 补充一点 : 把cocoapod的安装源改为https://gems.ruby-china.org 可以实现不需要翻墙即可安装GoogleMaps
    打开命令终端 ,具体如下:
    $ gem sources --add https://gems.ruby-china.org/ --remove https://rubygems.org/
    $ gem sources -l https://gems.ruby-china.org
    # 确保只有 gems.ruby-china.org

需要配置的库

d.这里我们只需要其中一些有用的文件,如下图:

1BE8FA5C-23EA-495F-97A8-A76D6ADCEF3C.png

e.把上面的4个文件拷贝出来,放到自定义的同一个文件夹,然后拖进自己的项目中 如下图:

  • 开始集成---
    首先最简单的方法就是用Cocoapods集成。但是你会发现因为Google被和谐,GoogleMaps也不能直接用Cocoapods集成。在此又一次吐槽天朝的权威。被和谐了怎么办。有两条路:
    1.继续使用Cocoapods集成,毕竟这是最简单快捷的。但是我们需要一个VPN来帮助我集成。这里推荐一些免费试用的VPN 如:行云VPN(自己百度去,提示一下,线路要用“下载专线”)。
    如果用行云vpn,最终会生成如下图的连接,连接上VPN就静静等待Cocoapods集成。亲测可用

f.接下来的步骤,可以参考前言提到的文章《http://www.jianshu.com/p/dc7d267d63d0 》
为使Google Maps SDK正常工作,需要包含几个其他的框架到工程中。在我给你必须添加的框架和静态库列表之前,请保证在Project Navigator中选择工程,点击Build Phases并展开Link Binary With Libraries选项。使用加号( )按钮来按下面的列表来逐项增加:

C3BA4B6D-8C9F-4047-9092-1834841291F3.png

彩民之家论坛9066777 20

3DCF5857-3F3A-405A-BA06-BED8AA68B1CD.png

c.下载好的GoogleMaps解压后如下图:

版权声明:本文由彩民之家高手论坛发布于编程技术,转载请注明出处:Android GoogleMap定位集成彩民之家论坛9066777