2012-12-08 43 views
18

Tôi gặp sự cố khi tôi muốn nhận vị trí hiện tại.Nhận vị trí hiện tại trên Google Map

Đây là lần đầu tiên tôi sử dụng API GM này và có rất nhiều điều tôi không hiểu.

Đây là mã của tôi, và tôi muốn

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 
    }); 
} 

Vấn đề là, tôi muốn thay đổi -7,7801502 và 110,3846387 giá trị tự động dựa trên vị trí hiện tại của người dùng. Tôi có thể làm điều đó?

Cảm ơn trước sự giúp đỡ và giải thích của bạn.

Một câu hỏi khác: -> Điều gì xảy ra nếu tôi sẽ thay đổi giá trị đó dựa trên thiết bị được nhúng bằng GPS?

Trả lời

27

Bạn không thể có được vị trí của người dùng hiện tại bằng Google Maps. Tuy nhiên, nếu bạn sử dụng Google Maps với Google Loader, bạn có thể sử dụng google.loader.CurrentLocation để nhận vị trí dựa trên IP.

Một cách khác là sử dụng 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)); 
} 
+0

Đối với hầu hết các trình duyệt giao thức an toàn https bây giờ yêu cầu cho các API HTML5 geolocation – ZimSystem

1

Nếu bạn muốn ở lại trong thế giới của bản đồ google API, và giả sử bạn có biến bản đồ mà bạn có thể sử dụng,

var map = new google.maps.Map(document.getElementById("map-canvas"), 
     mapOptions); 

var myLat = map.center.k; 
var myLng = map.center.B; 

hoặc bạn có thể sử dụng,

alert("Lat="+map.center.k); 
alert("Lng="+map.center.B); 
-1
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!!!!" 
        } 

       } 


      } 
     } 
    } 
} 

...

+0

Trong khi đoạn mã này có thể giải quyết các câu hỏi, [trong đó có một lời giải thích] (http://meta.stackexchange.com/ câu hỏi/114762/giải thích toàn bộ mã dựa trên câu trả lời) thực sự giúp cải thiện chất lượng bài đăng của bạn. Hãy nhớ rằng bạn đang trả lời câu hỏi cho người đọc trong tương lai và những người đó có thể không biết lý do cho đề xuất mã của bạn. – Isma

Các vấn đề liên quan