【问题标题】:Get Current Location On Google Map在谷歌地图上获取当前位置
【发布时间】:2012-11-26 15:56:21
【问题描述】:

当我想获取当前位置时遇到了一些麻烦。

这是我第一次使用这个GM API,还有很多我不明白的地方。

这是我的代码,我想要

var geocoder = new google.maps.Geocoder();

function initialize() {
  var latLng = new google.maps.LatLng(-7.7801502, 110.3846387);
  var map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 15,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var marker = new google.maps.Marker({
    position: latLng,
    title: 'Ambarrukmo Plaza Yogyakarta',
    map: map,
    draggable: true
  });
}

问题是,我想根据用户的当前位置自动更改 -7.7801502 和 110.3846387 值。我可以这样做吗?

之前感谢您的帮助和解释。

另一个问题: -> 如果我要根据嵌入 GPS 的设备更改这些值怎么办?

【问题讨论】:

    标签: google-maps google-maps-api-3


    【解决方案1】:

    您无法通过 Google 地图获取当前用户的位置。但是,如果您使用 Google Loader 获取 Google 地图,则可以使用 google.loader.CurrentLocation 获取基于 IP 的位置。

    另一种方法是使用HTML5 GeoLocation API

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        alert("Geolocation is not supported by this browser.");
      }
    }
    function showPosition(position) {
      var lat = position.coords.latitude;
      var lng = position.coords.longitude;
      map.setCenter(new google.maps.LatLng(lat, lng));
    }
    

    【讨论】:

    • 对于大多数浏览器来说,HTML5 GeoLocation API 现在需要安全的 https 协议
    【解决方案2】:

    对于在未来寻找解决方案的人,Google 现在在 Google 地图页面上提供了地理定位示例 > https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

    【讨论】:

      【解决方案3】:

      如果你想留在谷歌地图 API 的世界里,并且假设你有可以使用的地图变量,

      var map = new google.maps.Map(document.getElementById("map-canvas"),
              mapOptions);
      
      var myLat = map.center.k;
      var myLng = map.center.B;
      

      或者你可以使用,

      alert("Lat="+map.center.k);
      alert("Lng="+map.center.B);
      

      【讨论】:

        【解决方案4】:
        import UIKit
        import GoogleMaps
        import GooglePlaces
        import CoreLocation
        
        class ViewController: UIViewController,CLLocationManagerDelegate,GMSMapViewDelegate {
        
        @IBOutlet weak var currentlocationlbl: UILabel!
        
        
        var mapView:GMSMapView!
        
        var locationManager:CLLocationManager! = CLLocationManager.init()
        
        var geoCoder:GMSGeocoder!
        
        var marker:GMSMarker!
        
        var initialcameraposition:GMSCameraPosition!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        
            self.mapView = GMSMapView()
            self.geoCoder = GMSGeocoder()
            self.marker = GMSMarker()
            self.initialcameraposition = GMSCameraPosition()
        
            // Create gms map view------------->
            mapView.frame = CGRect(x: 0, y: 150, width: 414, height: 667)
            mapView.delegate = self
            mapView.isMyLocationEnabled = true
            mapView.isBuildingsEnabled = false
            mapView.isTrafficEnabled = false
            self.view.addSubview(mapView)
        
            // create cureent location label---------->
        
            self.currentlocationlbl.lineBreakMode = NSLineBreakMode.byWordWrapping
            self.currentlocationlbl.numberOfLines = 3
            self.currentlocationlbl.text = "Fetching address.........!!!!!"
        
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
            if locationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization))
            {
                self.locationManager.requestAlwaysAuthorization()
            }
            self.locationManager.startUpdatingLocation()
        
            if #available(iOS 9, *)
            {
            self.locationManager.allowsBackgroundLocationUpdates = true
            }
            else
            {
                //fallback earlier version
            }
            self.locationManager.startUpdatingLocation()
        
        
            self.marker.title = "Current Location"
            self.marker.map = self.mapView
        
        
            // Gps button add mapview
        
            let gpbtn:UIButton! = UIButton.init()
            gpbtn.frame = CGRect(x: 374, y: 500, width: 40, height: 40)
            gpbtn.addTarget(self, action: #selector(gpsAction), for: .touchUpInside)
            gpbtn.setImage(UIImage(named:"gps.jpg"), for: .normal)
            self.mapView.addSubview(gpbtn)
            }
        
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
        {
            var location123 = CLLocation()
        
            location123 = locations[0]
        
            let coordinate:CLLocationCoordinate2D! = CLLocationCoordinate2DMake(location123.coordinate.latitude, location123.coordinate.longitude)
        
            let camera = GMSCameraPosition.camera(withTarget: coordinate, zoom: 16.0)
        
            self.mapView.camera = camera
            self.initialcameraposition = camera
            self.marker.position = coordinate
            self.locationManager.stopUpdatingLocation()
        
        }
        
        
        func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition)
        {
            self.currentAddres(position.target)
        }
        
        func currentAddres(_ coordinate:CLLocationCoordinate2D) -> Void
        {
            geoCoder.reverseGeocodeCoordinate(coordinate) { (response, error) in
        
                if error == nil
                {
                    if response != nil
                    {
        
                        let address:GMSAddress! = response!.firstResult()
        
                        if address != nil
                        {
                           let addressArray:NSArray! = address.lines! as NSArray
        
                            if addressArray.count > 1
                            {
                                var convertAddress:AnyObject! = addressArray.object(at: 0) as AnyObject!
                                let space = ","
                                let convertAddress1:AnyObject! = addressArray.object(at: 1) as AnyObject!
                                let country:AnyObject! = address.country as AnyObject!
        
                                convertAddress = (((convertAddress.appending(space) + (convertAddress1 as! String)) + space) + (country as! String)) as AnyObject
        
                                self.currentlocationlbl.text = "\(convertAddress!)".appending(".")
                            }
                            else
                            {
                                self.currentlocationlbl.text = "Fetching current location failure!!!!"
                            }
        
                        }
        
        
                    }
                }
            }
        }
        

        ...

        【讨论】:

        • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
        猜你喜欢
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多