ios - webview中的Google地图未加载当前位置

时间:2016-06-07 20:51:38

标签: ios objective-c google-maps webview

我创建了一个带有html的webview来加载当前用户的位置。

这是使用的结构:

webview.m - 加载index.html

index.html - 显示数据

info.plist - NSLocationWhenInUseUsageDescription&添加了NSLocationAlwaysUsageDescription

以下是两种情况:

1)如果我在Webview中加载Google地图 - 它不会加载我当前的位置。旋转器只是旋转并显示世界地图。

2)在index.html中,我添加了加载当前位置经度和纬度的代码。在笔记本电脑的浏览器(不是xcode)它显示我的位置,如果我在xcode中打开index.html它没有显示我。

可能需要添加一些内容才能让应用获取您的位置,例如在浏览器上它要求获得位置许可。在应用程序中,它没有问我这个。

这是代码: webview.m

#import "Webview.h"

@interface Webview ()

@end

@implementation Webview

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


    NSString *urlAddress= [[NSBundle mainBundle] pathForResource:@"demos/index" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath: urlAddress];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL: url];

    [_webView setDelegate:self];
    _webView.scrollView.delegate = self;
    _webView.scrollView.scrollEnabled = true;
    _webView.scrollView.bounces = NO;
   [_webView loadRequest:requestObj];





}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end

的index.html

加载谷歌地图

<meta http-equiv="refresh" content="0; url=http://maps.google.com/" />

加载当前位置

  <p>Address:
        <div id="address"></div>
         <div id="l"></div>
         <div id="lo"></div>
    </p>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
    <script type="text/javascript">
    $(document).ready(function () {

    var currgeocoder;

    //Set geo location lat and long
    navigator.geolocation.getCurrentPosition(function (position, html5Error) {
        geo_loc = processGeolocationResult(position);
        currLatLong = geo_loc.split(",");
        initializeCurrent(currLatLong[0], currLatLong[1]);
    });

    //Get geo location result
    function processGeolocationResult(position) {
        html5Lat = position.coords.latitude; //Get latitude
        html5Lon = position.coords.longitude; //Get longitude
        html5TimeStamp = position.timestamp; //Get timestamp
        html5Accuracy = position.coords.accuracy; //Get accuracy in meters
        return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
    }

    //Check value is present or
    function initializeCurrent(latcurr, longcurr) {
        currgeocoder = new google.maps.Geocoder();

        console.log(latcurr + "-- ######## --" + longcurr);

        if (latcurr != '' && longcurr != '') {
            //call google api function
            var myLatlng = new google.maps.LatLng(latcurr, longcurr);
            return getCurrentAddress(myLatlng);
        }
    }

    //Get current address
    function getCurrentAddress(location) {
        currgeocoder.geocode({
            'location': location
        }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                console.log(results[0]);
                $("#address").html(results[0].formatted_address);
                $("#l").html(html5Lat);
                $("#lo").html(html5Lon);   

            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
});
    </script>

info.plist中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIcons</key>
    <dict/>
    <key>CFBundleIcons~ipad</key>
    <dict/>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>NSLocationWhenInUseUsageDescription </key>
    <string>Give us permission to use your location</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>Your message goes here</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>UILaunchStoryboardName</key>
    <string>Main</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>akamaihd.net</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                <false/>
            </dict>
            <key>facebook.com</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                <false/>
            </dict>
            <key>fbcdn.net</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                <false/>
            </dict>
        </dict>
    </dict>
</dict>
</plist>

问题:如何让我的应用程序询问位置权限?或直接加载位置?

1 个答案:

答案 0 :(得分:0)

问题:如何让我的应用程序询问位置权限?或直接加载位置?

首先,这里有一个SO thread可能会提供使用UIWebView显示地图的解决方案。

现在关于iOS地图中的权限:

尝试使用locationManager(_:didChangeAuthorizationStatus:)启用权限。这意味着您在使用应用程序时授予用户权限。

extension MapViewController: CLLocationManagerDelegate {

  func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

    if status == .AuthorizedWhenInUse {

      locationManager.startUpdatingLocation()
      mapView.myLocationEnabled = true
      mapView.settings.myLocationButton = true
    }
  }

  func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {

      mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

     locationManager.stopUpdatingLocation()
    }

  }
}

完整的教程check this