I'm using Google Maps Javascript Web API. I'm looking to get the current location (GPS coordinates) of the view. Meaning, if I drag the map all the way to England, the function would return the GPS coordinates of the view's center (which would be somewhere in England).
How can it be accomplished? Is there a certain function I can use?
Try getCenter():
let map = new google.maps.Map(document.getElementById('map'), { ... }),
currentLocation = map.getCenter();
Demo
Related
I am trying to make an uber type app with nativescript but I am struggling to find a way to center a position when an app opens just like when you open uber app. I am using google maps API
Thank you
If you're using the nativescript-google-maps-sdk (which I think you are since you also posted the question over there) then you can do this:
// Any value from 2 to 20
mapView.zoom = 15;
// Moves the map
mapView.latitude = lat;
mapView.longitude = lng;
// Places the marker at the point
marker.position = mapsModule.Position.positionFromLatLng(lat, lng);
I want to:
Render a google map on a web page;
Have the map centre on a user's current location;
Show places local to that user.
Question: Assuming this is possible (and that the limiting factor is my current ability), how might this be achieved?
Resources:
I am using the Google Maps JS API v3 and Places Library
Currently, I can achieve either rendering places around a hardcoded location or centring the map on the user.
I have used this Geolocation code and this Places Search code assuming that I could integrate the code of one into the other (by handing lat/long values from the geolocator into the location object pyrmont).
There exists a SO question on this for Google Maps API v2, deprecated by v3.
First thing you need to do is define the map:
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&libraries=places&callback=initMap" async defer></script>
this tells us that we are using the places library and on callback we are going to call the initMap function.
function initMap() {
var london = {
lat: 51.5073509,
lng: -0.12775829999998223
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
london = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(london);
setPlaces(london);
});
} else {
// Browser doesn't support Geolocation
//since you set coords above this section it will default to that
setPlaces(london);
}
map = new google.maps.Map(document.getElementById('map'), {
center: london,
zoom: 15
});
}
The initMap function initialises the map. We set var london to the co-ordinates of London in case the user does not have location turned on.
We then check to see if their location is turned on if (navigator.geolocation) {does this. if this is true then we override london to the users position. If changed we then move the map to the users location.
both outcomes will call:
function setPlaces(location) {
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: location,
radius: 1000,
type: ['store']
}, callback);
}
Which gets the places around the location (either user or predefined)
A working example can be seen here, for parameters etc just read the API.
JSFIDDLE: https://jsfiddle.net/4kgy68rg/1/
I'm using Mapbox for a dynamic map on a social website.
I added a satellite toggle button but I can't find any way in the API docs on how to switch from terrain view to satellite view like Google Maps does?
Is it hidden somewhere? I know I have to subscribe and I will but I need to know I can switch from terrain to satellite in realtime without losing my markers, etc.
Let's say I have a simple map:
var initialLocation = [40.97, 64.07];
var initialZoomLevel = 2;
var map = L.mapbox.map('map_container').setView(initialLocation, initialZoomLevel);
How could I switch from terrain to satellite?
Any suggestions?
Thanks!
Its pretty easy to add a satellite view - just not very well documented. A prerequisite though is you must have a paid account (UPDATE: you used to need a paid account - that no longer seems to be the case) and have setup your own map in your account over there with the satellite imagery selected.
var initialLocation = [40.97, 64.07];
var initialZoomLevel = 2;
var map = L.mapbox.map('map_container').setView(initialLocation, initialZoomLevel);
L.control.layers({
"Street": map.tileLayer,
"Satellite": L.mapbox.tileLayer("my satellite imagery map id")
}, null).addTo(map);
This adds a control in the upper right (by default) that allows you to select between the default map and your satellite map.
With MapBox there is no concept of "modes", just different maps each with their own Map ID. So create a map at http://tiles.mapbox.com/newmap based on terrain, then another based on satellite imagery. Switch between them with the second argument to L.mapbox.map (see http://www.mapbox.com/mapbox.js/api/#L.mapbox.map) using their respective IDs.
i have a problem that i want to zoom to place using esri javascript api
i have this class from esriGetStarted javascript
function zoomToPlace(lon, lat, scale) {
mapDeferred.centerAndZoom([lon, lat], scale);
}
i have tried to zoom to place using this html element :
zoom to place
but it never work untill now, please help me how to zoom to place, or may be is there alternative.
You may be having spatial reference issues (first port of call for any error with a mapping engine :) ). My code from an existing project converts the coordinates to web mercator before attempting to zoom to it:
var pt = esri.geometry.geographicToWebMercator(new esri.geometry.Point(lon, lat));
_map.centerAndZoom(pt, scale);
Not sure if this will help, but there is a Locate Widget in the ESRI API:
require(["esri/dijit/LocateButton"],
geoLocate = new LocateButton({
map: map
}, "LocateButton");
geoLocate.startup();
I have read up on GPS Real time tracking and found out several things about it, mostly requiring PHP, zope and a database to store the incoming data. Some other methods uses ajax with relations to PHP.
As regards to my question, is it possible to do so with just html and JS, using markers or anything else to populate the Google Map when you move anywhere in the city? Need some help on this, Thanks!
Yes, it is possible. Most browsers in the latest smartphones have implemented the W3C Geolocation API:
The Geolocation API defines a high-level interface to location information associated only with the device hosting the implementation, such as latitude and longitude. The API itself is agnostic of the underlying location information sources. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input. No guarantee is given that the API returns the device's actual location.
The API is designed to enable both "one-shot" position requests and repeated position updates, as well as the ability to explicitly query the cached positions.
Using the Geolocation API to plot a point on Google Maps, will look something like this:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var point = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: point,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Place a marker
new google.maps.Marker({
position: point,
map: map
});
});
}
else {
alert('W3C Geolocation API is not available');
}
The above will only gather the position once, and will not auto update when you start moving. To handle that, you would need to keep a reference to your marker, periodically call the getCurrentPosition() method, and move the marker to the new coordinates. The code might look something like this:
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = null;
function autoUpdate() {
navigator.geolocation.getCurrentPosition(function(position) {
var newPoint = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map
});
}
// Center the map on the new position
map.setCenter(newPoint);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 5000);
}
autoUpdate();
Now if by tracking you mean that you should also store this information on a server (so that someone else could see you moving from a remote location), then you'd have to send the points to a server-side script using AJAX.
In addition, make sure that the Google Maps API Terms of Use allow this usage, before you engage in such a project.
UPDATE: The W3C Geolocation API exposes a watchPosition() method that can be used instead of the setTimeout() mechanism we used in the above example.