在谷歌地图上获取当前位置

25

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

这是我第一次使用这个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的设备更改这些值会怎样?

5个回答

39

使用Google Maps无法获取当前用户的位置。但是,如果您使用Google Loader获取Google Maps,则可以使用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));
}

1
对于大多数浏览器,HTML5 GeoLocation API现在需要安全的https协议。 - Carol Skelly

9

1
如果您想留在Google Maps 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);

0
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!!!!"
                    }

                }


            }
        }
    }
}

...


4
虽然这段代码片段可能解决了问题,但包括解释确实有助于提高您的帖子质量。请记住,您正在为未来的读者回答问题,那些人可能不知道您提出代码建议的原因。 - Isma

0

对于那些感兴趣的人,另一种建议的方法是获取用户当前位置,然后显示谷歌地图。

https://codepen.io/easyisez/pen/mdGgMdG

JS 代码:

(function (global) {
"use strict";

// Callback function passed: showMap
function getLocation(callback) {
    navigator.geolocation.getCurrentPosition(function (pos) {
        callback({
            "latitude": pos.coords.latitude,
            "longitude": pos.coords.longitude,
            "status": 0,
            "description": ""});
    }, function (err) {
        // Failure reported by the browser's getCurrentPosition method
        callback({
            "latitude": null,
            "longitude": null,
            "status": -1,
            "description": `ERROR (${err.code}): ${err.message}`});
    });
}


$(document).ready(function () {
    var showMap = function (appState) {
        if (appState.status === 0) {
            var map = new google.maps.Map(document.getElementById('map'), {
                    center: {lat: appState.latitude, lng: appState.longitude},
                    zoom: 20,
                    mapTypeId: 'satellite',
                    streetViewControl: false
            });
            
        } else {
            // Handle error
        }
    }

    // Disable AJAX caching
    $.ajaxSetup({cache: false});

    // Get the weather for the current location
    getLocation(showMap);

});

}(this));

更多细节请访问我的 CodePen 项目。祝您使用愉快。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接