I'm using MapBox to plot points of interest that is submitted through a user generated form built on rails. Currently the user enters a address, then the address has it's Lat and Lng calculated through a gem (geocoder). There from I pass the data from rails to javascript via the gon gem, run a forEach loop on all the points of interest, and then plot on the map using the lat and lng.
Now I want to get driving directions between the points of interest, a to b to c, etc. MapBox has a directions section, but the directions are based on the click event on the map, not stored input. Been wrestling with this for a while, and google hasn't been fruitful.
Links and advice on how to get directions between my plotted points using MapBox is hugely appreciated.
Cheers.
When using the Mapbox directions API you can supply your own waypoints, a semicolon separated list of coordinates.
http://api.tiles.mapbox.com/v4/directions/{profile}/{waypoints}.json?access_token=<your access token>
Waypoints should minimaly consist of two coordinates, your start and destination coordinates. This API should do exactly what you want. More information about on the Mapbox direction API can be found here
I don't know mapBox. But notice: it is the browser that tells you your location; it's not Google Mpas, mapBox or ...
<script type="text/javascript">
function initialize(position, accuracy) {
alert(
'Lat: ' + position.lat + ' - Lng' + position.lng + ' - accuracy: ' + accuracy + 'm'
);
//// example for Google Maps
// var latlng = new google.maps.LatLng(position.lat, position.lng);
// ...
}
// request is succesful
function locationFound(position) {
initialize(
{lat: position.coords.latitude, lng: position.coords.longitude},
position.coords.accuracy
);
}
function locationNotFound() {
alert('Not able to find your location');
}
function page_loaded() {
// the page is loaded, we can send a request to search for the location of the user
navigator.geolocation.getCurrentPosition(locationFound, locationNotFound);
}
</script>
<body onload="page_loaded()">
<div id="map-canvas"></div>
</body>
Related
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
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 am currently integrating Google Maps Javascript API. I would like for the user to be able to type an address and have a "google street view" map generated for him. Preferrably, this street view map should be looking "inside" the office building. Example:
I am searching for "Zar Restaurant & Bar, Rosenheimer Straße, Munich, Germany" in Google Maps (link: https://www.google.bg/maps/place/Zar+Restaurant+%26+Bar/#48.1141096,11.6115833,17z/data=!3m1!4b1!4m5!3m4!1s0x479ddf9443819fc1:0xb242780e5bdc5ce5!8m2!3d48.114106!4d11.613772?hl=en). One business is found, and if you click on the image in the side panel, you are shown a 3d-view inside the restaurant.
Alternatively, if a Google organic search is made with the same keywords, the business listing is displayed on the right and there is a button saying "see inside" that gets you there. I would like to achieve such a 3d-view map (showing the inside view) embedded on the site, as shown here: http://www.zar-bar.de/galerie.php . I am sure that this can be easily achieved by embeding the iframe google generates for you, but i would like NOT to use this method.
Question: How to get the same 3d view inside the business through Google Maps Javascript API?
I know that the same map can be displayed by the JS API when you enter the lat & lng. I managed to find the needed lat & lng from this tool of theirs: https://developers.google.com/maps/documentation/embed/start. From here, i saw the lat & lng from the params in the iframe src just below the imag . Then i placed the coordinates in google maps js api and it worked. Working code:
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var position = {lat: 48.1141, lng: 11.6138};
var map = new google.maps.Map(document.getElementById('someDiv'), {
center: position,
zoom: 14
});
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('someDiv'), {
position: position,
pov: {
heading: 240,
pitch: 10
}
});
map.setStreetView(panorama);
}
JS Fiddle: https://jsfiddle.net/cdfnvrj0/3/. This lead me to believe that i need to get the lat & lng from a an address.
What i have tried:
Requesting Google Maps geocode API to get lat & lng from an address with the following request URL:
"https://maps.googleapis.com/maps/api/geocode/json?address=Zar%20Restaurant%20Bar,%20Rosenheimer%20Stra%C3%9Fe,%20Munich,%20Germany%20&key=AIzaSyBLASrj4k7gOpG62kdBWwGrGyHnfM71FT4"
This API finds the address and returns some geolocation data, but when i place these coordinates in my google maps JS api, the displayed position is not exactly the same. It places me somewhere on the street, not a 3d view of the searched business. This leads me to believe that this API returns geolocation based on the address as it is, and not an address of a business, i.e does not work for businesses. So, how does one figure out if there is a Google My Business address corresponding to a given address (through an API), and if there is such a business, how can i find out if it has an "inside view", and how can i take it's lat&lng to place it on a map? Is this currently possible with Google APIs?
I would be very thankful of all feedback and suggestions. Thank you for your time.
The geocoder is for postal addresses. To find a "place" (like "Zar Restaurant Bar"), use the Places API
Places API result for "Zar Restaurant Bar, Rosenheimer Straße, Munich, Germany":
Rosenheimer Str. 240, 81669 München, Germany (48.114106, 11.61377200000004)
Geocoder API result for "Zar Restaurant Bar, Rosenheimer Straße, Munich, Germany":
Rosenheimer Str., München, Germany (48.1232636, 11.602944500000035) ["GEOMETRIC_CENTER"/"partial_match"]
I am working on an AIR Android project and I needed to give the user an option to select a location from a map. Everything else works perfectly. I am able to transfer selected lats and lngs from JS to AS. But I also want the map to center it's position to user's location when it first loads up. To do that I followed the google maps documentation and it worked perfectly in HTML. But it turns out "Geocoder" doesn't work in StageWebView. So after lots of failing I decided to use AS3's geolocation services and send Lats and Lngs from AS3 to JS when the maps loads up. To do that, in AS I find the user's position and user the following JS injection inside the WebViewLoaded event:
webView.loadURL("javascript:setMapCenter('" + _lats + "', '" + _lngs + "')");
Now here is the setMapCenter function in JS:
function setMapCenter(lats, lngs){
ASLats = lats;
ASLngs = lngs;
pos = {
lat: ASLats,
lng: ASLngs
};
// map.setCenter({lat:ASLats, lng:ASLngs});
map.setCenter(pos);
alert("set map center function was called with " + pos.lat + " " + pos.lng);
}
When I run AIR project, and open the map. As soon as the map loads, I get the alert window showing the lats and lngs recieved from AS3. Which means the injection is correct and the values are being successfully send from AS to JS. The problem is
map.setCenter({lat:ASLats, lng:ASLngs});
or
map.setCenter(pos);
doesn't really work. The map doesn't center itself correctly. But when I call the same function insde the
window.onload(){};
in JS like this
setMapCenter(50.256498, -0.25468);
it works perfectly.
I really don't understand why it doesn't work. It's getting pretty frustrating. I am sorry if it sounds like a dumb question. I actually have no prior experience with JS. This is the first I am working with it. So any help will be really appreciated.
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.