2016-06-07 3 views
1

Я создал webview с html в нем, чтобы загрузить текущее местоположение пользователей.ios - Google maps in webview не загружает текущее местоположение

Здесь используется структура:

webview.m - грузы index.html

index.html - показывает данные

info.plist - NSLocationWhenInUseUsageDescription & NSLocationAlwaysUsageDescription добавлено

здесь две ситуации:

1) Если я загружаю Карты Google в Webview - это d oes не загружает мое текущее местоположение. Прядильщик просто крутится и показывает карту мира.

2) В index.html Я добавляю код для загрузки моего текущего местоположения долготы и широты. В браузере ноутбука (не xcode) он показывает мое местоположение, если я открываю index.html в xcode, это не показывает мне его.

Возможно, есть что добавить, чтобы приложение могло получить ваше местоположение, например. в браузере он запрашивает разрешение на размещение. В приложении это меня не спрашивает.

Вот код: 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

загрузки Google Maps

<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> 

Вопрос: как разрешить моему приложению запрашивать разрешение на размещение? или загрузить местоположение сразу?

ответ

0

Вопрос: как разрешить моему приложению запрашивать разрешение на размещение? или загрузить местоположение сразу?

Первый, вот SO thread, который может предложить решение при отображении карт с использованием UIWebView.

Теперь в отношении разрешений на IOS Maps:

Попробуйте включить разрешение с помощью 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.

Смежные вопросы