get the elevation of a googlemaps' marker - google-maps

I try to get the elevation of a point on a map, but the elevation function proposed by the googlemaps' API doesn't work and I don't know why.
It seems that the programm don't even get through the function.
Here my function :
var elevationService = new google.maps.ElevationService();
var requestElevation = {
'locations': gmarkers[0].getPosition()};
elevationService.getElevationForLocations(requestElevation, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
if (results[0]) {
document.getElementById('denivele_circuit').value = parseFloat(results[0].elevation.toFixed(1)) + "mètres";
}
} });

I get a javascript error with your code: Uncaught InvalidValueError: in property locations: not an Array
The locations property in the LocationElevationRequest must be an array.
from the documentation for google.maps.LocationElevationRequest object specification
An elevation request sent by the ElevationService containing the list of discrete coordinates (LatLngs) for which to return elevation data.
Properties
locations Type: Array
The discrete locations for which to retrieve elevations.
var requestElevation = {
'locations': [gmarkers[0].getPosition()]
};
proof of concept fiddle
code snippet:
var gmarkers = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
gmarkers.push(marker);
var elevationService = new google.maps.ElevationService();
var requestElevation = {
'locations': [gmarkers[0].getPosition()]
};
elevationService.getElevationForLocations(requestElevation, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
if (results[0]) {
document.getElementById('denivele_circuit').value = parseFloat(results[0].elevation.toFixed(1)) + " mètres";
}
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input id="denivele_circuit" />
<div id="map_canvas"></div>

Related

Google maps geocoding with bounds

With the following code when I get a result back, I don't appear to get the full address components of the result back, which we are using with our other services to determine various things.
As soon as I take the bounds out, it works fine. But I still need it restricted to the bounds.
Why is this? and how can I solve the issue?
CODE:
_geocoder.geocode(_.extend(position, {
bounds: {
west: -25.806884999999966,
east: 16.380615000000034,
south: 48.98742739340465,
north: 60.16884190739975
}
}), function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
_lastResults = results;
deferred.resolve(results);
} else {
deferred.reject('Geocode was not successful for the following reason: ' + status);
}
});
To add the bounds to the GeocoderRequest, it goes inside the request object:
var data = {
bounds: {
west: -25.806884999999966,
east: 16.380615000000034,
south: 48.98742739340465,
north: 60.16884190739975
}
};
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(data.bounds.south, data.bounds.west),
new google.maps.LatLng(data.bounds.north, data.bounds.east));
geocoder.geocode({
address: "London",
bounds: bounds
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
Note however:
Optional parameters:
bounds — The LatLngBounds within which to bias geocode results more prominently. The bounds parameter will only influence, not fully restrict, results from the geocoder. (For more information see Viewport Biasing below.)
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var data = {
bounds: {
west: -25.806884999999966,
east: 16.380615000000034,
south: 48.98742739340465,
north: 60.16884190739975
}
};
var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(data.bounds.south, data.bounds.west), new google.maps.LatLng(data.bounds.north, data.bounds.east));
var rectangle = new google.maps.Rectangle({
map: map,
bounds: bounds
});
map.fitBounds(bounds);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: "London",
bounds: bounds
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

How to find the exact location details from latitude and longitude?

I tried using Google Maps API for 'Reverse Geocoding' to get the location by providing latitude and longitude. This gives the street address, city and country info. But I need to get the exact details like building name, shop name etc. For example, while querying the co-ordinates "72.9011206,19.0517508", Google Maps API gives "Plot No 5, VN Purav Marg, Borla, Union Park, Chembur, Mumbai, Maharashtra 400071, India". But I need to get the name of the shop "Barista Lavazza" as available in 'Google Earth' for the same co-ordinate details.
One option would be to use the Google Maps Javscript API Places library nearbySearch, search the returned results for the closest result to the requested position.
proof of concept fiddle
code snippet:
var map;
var infowindow;
var searchLoc = new google.maps.LatLng(19.0517508, 72.9011206);
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: searchLoc,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow();
var request = {
location: searchLoc,
radius: '50'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var bounds = new google.maps.LatLngBounds();
var distMin = Number.MAX_VALUE;
var idxMin = -1;
for (var i = 0; i < results.length; i++) {
var place = results[i];
bounds.extend(results[i].geometry.location);
var distance = google.maps.geometry.spherical.computeDistanceBetween(results[i].geometry.location, searchLoc);
if (distance < distMin) {
distMin = distance;
idxMin = i;
}
}
var marker = createMarker(results[idxMin]);
google.maps.event.trigger(marker, 'click');
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<h2 style='color:blue'>"+place.name + "</h2><br>" + place.vicinity + "<br>" + marker.getPosition().toUrlValue(7));
infowindow.open(map, this);
});
return marker;
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<div id="map_canvas"></div>

Pass Google Maps SearchBox result to Directions Service

After reading documentation for the SearchBox class, the Places library including the AutoComplete class, and the Directions service, I cannot figure out how to pass the address selected by a user from the SearchBox to the Directions service to draw the map. The map and marker display correctly, and the SearchBox displays and functions correctly. On the "place_change" event, though, nothing happens. My code:
var rawlatitude = <?php echo $loc_lat; ?>;
var rawlongitude = <?php echo $loc_long; ?>;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude,longitude);
google.maps.event.addDomListener(window, 'load',initMap(latitude,longitude));
function initMap(lat,lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// listen to and respond to address search
var onChangeHandler = function() {
var location = searchBox.getPlaces();
var start = location.place_id;
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'place_change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: start,
destination: latlong,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if(status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
As Dr.Molle observed in his comment,
There is no place_changed-event for a SearchBox, it's an event for Autocomplete. The event for a SearchBox is called places_changed.
Also note that a SearchBox.getPlaces() returns an array with places
working fiddle
working code snippet:
var rawlatitude = 40.7127837;
var rawlongitude = -74.0059413;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude, longitude);
var viewport = {
"south": 40.4960439,
"west": -74.2557349,
"north": 40.91525559999999,
"east": -73.7002721
};
google.maps.event.addDomListener(window, 'load', function() {
initMap(40.735657, -74.1723667);
});
function initMap(lat, lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
draggable: true,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: viewport
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// listen to and respond to address search
var onChangeHandler = function() {
var locations = searchBox.getPlaces();
var start = locations[0].place_id;
var bounds = new google.maps.LatLngBounds();
bounds.extend(latlong);
bounds.extend(locations[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
position: locations[0].geometry.location,
map: map,
title: locations[0].name
})
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'places_changed', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: {
placeId: start
},
destination: {
location: latlong
},
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" />
<div id="map"></div>

Zooming and centering the geocoded place using google maps api

I am working with the google maps api for one of my application. I have a textbox in which the user enters place name. It should geocode the users place name given in the textbox and zoom and center to that geocoded place name. I am successful in the geocoding but zooming and centre is not as expected. The code and output snapshot is provided.The black rectangle in the image is the place name that was geocoded based on the user input in the textbox. But zooming and centering is somewhere in the corner of the map. I want it to make the geocoded place name in the center of map.
var mapProp = {
center: x,
zoom: 4,
disableDefaultUI: true,
mapTypeId: layer,
mapTypeControlOptions: {
mapTypeIds: [layer]
}
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapProp);
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
map.mapTypes.set(layer, new google.maps.StamenMapType(layer));
geocoder.geocode({
'address': place_name_filter
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert(place_name_filter + " not found");
console.log("status : ", status);
}
});
Place_name_filter is the variable which holds the the place name entered in the textbox.
Output_Snapshot_for_the_above_code
Expected_Output
To zoom to a result from the geocoder use map.fitBounds and the .geometry.viewport (or geometry.bounds) LatLngBounds in the response.
code snippet:
function initialize() {
var mapProp = {
center: {
lat: 25,
lng: -90
},
zoom: 4,
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapProp);
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
var place_name_filter = "Abilene, TX";
geocoder.geocode({
'address': place_name_filter
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert(place_name_filter + " not found");
console.log("status : ", status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googlemaps {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googlemaps"></div>

Google Maps API v3 multiple markers Infowindow

I've used the code below to display a map with multiple markers and infowindows. Now I have encountered the very common problem of the last infowindow showing up on all markers. I've tried all sorts of solutions including: http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/ and this one http://www.robertbolton.com/blog/google-maps-v3-multiple-markers-and-infowindows-in-a-loop but none of them fix the problem.
Here is my code:
var infowindow = null;
var geocoder;
var map;
$(document).ready(function() {
initialize();
});
function initialize() {
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, people);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
var people = [
{"userid":"47","lastname":"lastname1","firstname":"firstname1","address":"Paris, France","phone1":"00000000000","phone2":"","email":"me#me.com"},
{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"Versaille, France","phone1":"0","phone2":"0","email":"me#me.com"}
];
function setMarkers(map, people) {
for (var i = 0; i < people.length; i++) {
var p = people[i];
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
geocoding is an asynchronous request. So when you use geocoding inside the for-loop, the loop is already finished when you receive the results, i will always be 1 and point to the last item of people.
What you can do: split the marker-creation into 2 functions. 1 for the loop which calls the 2nd function that creates the markers:
remove the current function setMarkers and add the following 2 functions to your script:
function setMarkers(map,people) {
for (var i = 0; i < people.length; i++) {
setMarker(map, people[i])
}
}
function setMarker(map, people) {
var p=people;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
The rest of your script may stay as it is.