Get Latitude and Longitude Center of Google Map

how to get coordinates of the center of the viewed area in google maps using Google Maps JavaScript API v3

You can call:

map.getCenter();

to return a LatLng object.

How to center a Google Map to a latitude and longitude location?

You have to use

themap.setCenter(new google.maps.LatLng($(this).data('latitude'), $(this).data('longitude')));

All Google Maps javascript classes are referenced with the google.maps.ClassName() notation

Get Latitude and longitude center of Google Map

You are doing it right to get the center of the map by using the google maps's func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) delegate.

Take a variable for center coordinates

var centerMapCoordinate:CLLocationCoordinate2D!

Implement this delegate to know the center position.

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
let latitude = mapView.camera.target.latitude
let longitude = mapView.camera.target.longitude
centerMapCoordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
self.placeMarkerOnCenter(centerMapCoordinate:centerMapCoordinate)
}

Function to place a marker on center point

func placeMarkerOnCenter(centerMapCoordinate:CLLocationCoordinate2D) {
let marker = GMSMarker()
marker.position = centerMapCoordinate
marker.map = self.mapView
}

In this case you will get a lot of markers. So keep a global hold of marker and check if it is already present, just change the position

var marker:GMSMarker!

func placeMarkerOnCenter(centerMapCoordinate:CLLocationCoordinate2D) {
if marker == nil {
marker = GMSMarker()
}
marker.position = centerMapCoordinate
marker.map = self.mapView
}

Google Maps API - Get New Center Coordinates after map is moved

If you want the center values when it changes, use the 'center_changed' event:

center_changed
Arguments: None

This event is fired when the map center property changes.

google.maps.event.addListener(map, "center_changed", function() {
var center = this.getCenter();
var latitude = center.lat();
var longitude = center.lng();
console.log("current latitude is: " + latitude);
console.log("current longitude is: " + longitude);
});

proof of concept fiddle

code snippet:

function initMap() {  var myLatlng = {    lat: -25.363,    lng: 131.044  };
var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: myLatlng }); google.maps.event.addListener(map, "center_changed", function() { var center = this.getCenter(); var latitude = center.lat(); var longitude = center.lng(); console.log("current latitude is: " + latitude); console.log("current longitude is: " + longitude); });
}
html,body,#map {  height: 100%;  margin: 0;  padding: 0;}
<div id="map"></div><!-- Replace the value of the key parameter with your own API key. --><script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

Flutter: How can I get the coordinates of the center of the map in google maps?

Here is how to achieve it,


In short, this is the relevant code

void _onCameraMove(CameraPosition position) {
_lastMapPosition = position.target;
}


_onAddMarkerButtonPressed() {
_markers.clear();
setState(() {
_markers.add(Marker(
markerId: MarkerId(_lastMapPosition.toString()),
position: _lastMapPosition,
infoWindow: InfoWindow(title: _title, snippet: _detail),
icon: BitmapDescriptor.defaultMarker));
});
}

And here is full code, with all the generally required stuff,

        import 'dart:async';
import 'package:bazar/assets/colors/ThemeColors.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';

class LocationScreen extends StatefulWidget {
@override
_LocationChooserState createState() => _LocationChooserState();
}

class _LocationChooserState extends State<LocationScreen> {
Completer<GoogleMapController> _controller = Completer();
static const LatLng _center = const LatLng(45.343434, -122.545454);
final Set<Marker> _markers = {};
LatLng _lastMapPosition = _center;
MapType _currentMapType = MapType.normal;
String _title = "";
String _detail = "";

TextEditingController _lane1;
TextEditingController _lane2;
TextEditingController _lane3;

@override
void initState() {
super.initState();
_lane1 = new TextEditingController();
}

@override
Widget build(BuildContext context) {
double _height = MediaQuery.of(context).size.height;
double _width = MediaQuery.of(context).size.width;
return SafeArea(
child: Scaffold(
resizeToAvoidBottomPadding: true,
body: Stack(
children: [
GoogleMap(
mapToolbarEnabled: false,
// myLocationEnabled: true,
// myLocationButtonEnabled:true,
zoomControlsEnabled: false,
onMapCreated: _onMapCreated,
initialCameraPosition:
CameraPosition(target: _center, zoom: 11.0),
markers: _markers,
mapType: _currentMapType,
onCameraMove: _onCameraMove,
onTap: _handleTap,
),
Padding(
padding: EdgeInsets.all(20),
child: Align(
alignment: Alignment.topRight,
child: Column(
children: <Widget>[
_customButton(
FontAwesomeIcons.map, _onMapTypeButtonPressed),
SizedBox(
height: 15,
),
_customButton(
FontAwesomeIcons.mapMarker, _onAddMarkerButtonPressed),
SizedBox(
height: 5,
),
_customButton(FontAwesomeIcons.mapPin, _getUserLocation),
],
),
),
),
SlidingUpPanel(
minHeight: _height * 0.05,
maxHeight: _height * 0.4,
panel: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
height: 4,
width: _width * 0.2,
color: Orange,
),
SizedBox(
height: 10,
),
Container(
color: White,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
height: _height * 0.2,
width: _width,
color: White,
child: TextField(
maxLines: 4,
controller: _lane1,
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(4)),
borderSide:
BorderSide(width: 1, color: Orange),
),
errorBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(4)),
borderSide:
BorderSide(width: 1, color: Maroon),
),
errorStyle: TextStyle(
color: Orange.withOpacity(0.5)),
labelStyle: TextStyle(
color: Orange.withOpacity(0.5)),
labelText: "Address "),
cursorColor: Orange,
),
),
],
),
),
SizedBox(
height: 10,
),
Container(
child: InkWell(
onTap: () {
debugPrint("Save Address");
},
child: Container(
alignment: Alignment.center,
width: _width * 0.3,
height: 40,
padding: EdgeInsets.only(
left: 10, right: 10, top: 6, bottom: 6),
decoration: BoxDecoration(
color: Orange,
borderRadius: BorderRadius.circular(12)),
child: Text(
"Save",
style: TextStyle(
color: White,
fontSize: 20,
fontWeight: FontWeight.bold),
),
),
),
)
],
),
),
body: null)
],
),
// floatingActionButton: FloatingActionButton.extended(
// onPressed: _goToTheLake,
// label: Text('To the lake!'),
// icon: Icon(Icons.directions_boat),
// ),
),
);
}

void _onMapCreated(GoogleMapController controller) {
_controller.complete(controller);
}

void _onCameraMove(CameraPosition position) {
_lastMapPosition = position.target;
}

_customButton(IconData icon, Function function) {
return FloatingActionButton(
heroTag: icon.codePoint,
onPressed: function,
materialTapTargetSize: MaterialTapTargetSize.padded,
backgroundColor: White,
child: Icon(
icon,
size: 16,
color: Maroon,
),
);
}

_onMapTypeButtonPressed() {
setState(() {
_currentMapType = _currentMapType == MapType.normal
? MapType.satellite
: MapType.normal;
});
}

_onAddMarkerButtonPressed() {
_markers.clear();
setState(() {
_markers.add(Marker(
markerId: MarkerId(_lastMapPosition.toString()),
position: _lastMapPosition,
infoWindow: InfoWindow(title: _title, snippet: _detail),
icon: BitmapDescriptor.defaultMarker));
});
}

_handleTap(LatLng point) {
_markers.clear();
_getLocation(point);
setState(() {
_markers.add(Marker(
markerId: MarkerId(point.toString()),
position: point,
infoWindow: InfoWindow(title: _title, snippet: _detail),
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueOrange),
));
});
}

_getLocation(LatLng point) async {
final coordinates = new Coordinates(point.latitude, point.longitude);
var addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = addresses.first;
print("${first.featureName} : ${first.addressLine}");

setState(() {
_title = first.featureName;
_detail = first.addressLine;
_lane1.text = _title + " " + _detail;
});
}

_getUserLocation() async {
Position position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
final coordinates = new Coordinates(position.latitude, position.longitude);
var addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = addresses.first;
print("${first.featureName} : ${first.addressLine}");

final GoogleMapController controller = await _controller.future;
controller.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: LatLng(position.latitude, position.longitude), zoom: 16),
),
);

setState(() {
_title = first.featureName;
_detail = first.addressLine;
_lane1.text = _title + " " + _detail;
});
}
}

Hope it helps, I have a button to add a marker you can easily make it on the go, as required.

how to get center_changed latitude and longitude in angular google map

I found answer myself after a long workout given on google map events.

To get dragend lat and lng details change this code

dragend: function (mapModel, eventName, marker, orignalEventArgs) {
alert('dragend');
}

to

dragend: function (map, eventName) {
var center = map.getCenter();
$scope.latitude_n = center.lat();
$scope.longitude_n = center.lng(); console.log($scope.latitude_n+','+$scope.longitude_n); // center location details
},

If you want center_changed event lat and lng details add this code

center_changed:function (map, eventName){
var center = map.getCenter();
$scope.latitude_n = center.lat();
$scope.longitude_n = center.lng(); console.log($scope.latitude_n+','+$scope.longitude_n); // center location details
},

Good luck. Cheers.

Google Maps: get latitude and longitude from map element

The .data() method you are using on the element is jQuery syntax. To access a data atributes in pure Javascript you need to use .dataset.NAME. Learn more about accessing the data attributes here.

Your code updated:

var $map = document.getElementById('map');
var latitude = parseFloat($map.dataset.latitude);var longitude = parseFloat($map.dataset.longitude);var center = new google.maps.LatLng(latitude, longitude);

Unable to get latlong from center of the google map in android

You are probably trying to get the camera position when the map wasn't yet loaded. Instead wait for that with the OnMapLoadedCallback listener and get the center then:

mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
Log.e("TAG", googleMap.getCameraPosition().target.toString());
}
});

How to get latitude and longitude of center of google map



GEvent.addListener(map, "moveend", function() {
var center = map.getCenter();
});

How can i get location on center of screen with Google Map Api

As I can see you are trying to know the centre of the screen and drop a pin on it.(My assumption of your query.)
There are numerous posts on which you can try to get the centre point in XY coordinates with respect to the screen.
Check this link out https://stackoverflow.com/a/40714006/8117352.

After fetching these coordinates in X and Y points in screen you can use a concept of Projection in the google maps, which allows you to convert these points to latitude and longitude.


Point x_y_points = new Point(x_co, y_co);
LatLng latLng =
mGoogleMap.getProjection().fromScreenLocation(x_y_points);

More on projection : https://developers.google.com/android/reference/com/google/android/gms/maps/Projection



Related Topics



Leave a reply



Submit