Google Maps Elevation Service - google-maps

I have this function which is invoked upon clicking a button. The function creates a marker at a predefined position. I then use the elevation service for the given point. When I click the button, the alert message (I've put it there for diagnostics) displays 'undefined', and then the marker appears (in fact the marker should appear before the alert box!). I've tried my best to identify the source of the problem but in vain. Can anyone help me please? Thanks.
function buttonClicked () {
addNode(someLat, someLong);
alert(getElev(markers[0]));
}
function addNode(lat, lng) {
var LatLng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: LatLng,
});
marker.setMap(map);
markers.push(marker);
}
function getElev (marker) {
var ht = 0;
var locations = [];
var clickedLocation = marker.getPosition();
locations.push(clickedLocation);
var positionalRequest = {
'locations': locations
}
elevator.getElevationForLocations(positionalRequest, function (results, status) {
if (status == google.maps.ElevationStatus.OK && results[0])
ht = results[0].elevation;
});
return ht;
}

Add the alert here and it should work. The function inside getElevationForLocations does not occur within getElev, but is called asynchronously. so ht is not set within getElev.
elevator.getElevationForLocations(positionalRequest, function (results, status) {
if (status == google.maps.ElevationStatus.OK && results[0]){
ht = results[0].elevation;
alert(ht);
}
});

altitude = 0; // Declared with out "var" make it superglobal
function buttonClicked () {
addNode(someLat, someLong);
alert(getAltitude());
}
function addNode(lat, lng) {
var LatLng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: LatLng,
});
marker.setMap(map);
markers.push(marker);
}
function getElev (marker) {
var locations = [];
var clickedLocation = marker.getPosition();
locations.push(clickedLocation);
var positionalRequest = {
'locations': locations
}
elevator.getElevationForLocations(positionalRequest, function (results, status) {
if (status == google.maps.ElevationStatus.OK && results[0])
setAltitude(results[0].elevation);
});
}
//getters and setters for altitude
function setAltitude(a){
altitude = a;
}
function getAltitude(){
return altitude;
}

Related

Google Maps Nearby Search (Show Selected nearby markers only with autocomplete )

I have this code, which works fine, but there is just one issue which I am getting:
When we search nearby places, it appends the new nearby search markers with the old markers, screenshots are attached in these links.
Here I have searched the nearby banks:
http://prntscr.com/aouxra
It has successfully shown, but now if I search another nearby place like hotel, it will append its markers with the banks markers which has been searched previously, like this:
http://prntscr.com/aouz23
I want to only show the markers of the autocompleted nearby search query only.
function getNearby(lat,lng,map){
var availableTags = [
"hotel",
"bank",
"atm",
"school",
];
$( "#nearby" ).autocomplete({
source: availableTags,
select: function (event, ui) {
var request = null;
request = {
location: {lat:lat, lng:lng},
radius: 5500,
types: [ui.item.value]
};
var service = null;
var infowindow = null;
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
//var markers = [];
var markers = [];
var bounds = map.getBounds()
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++)
{
createMarker(results[i]);
//alert(results)
}
}
}
function createMarker(place) {
//markers.push(place);
var marker = '';
var placeLoc = '';
placeLoc = place.geometry.location;
marker = new google.maps.Marker({
map: map,
position: placeLoc
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
alert(markers.length);
}
});
}
function getLocation() {
$("#myNearby").css('display', 'block');
$("#directions").css('display', 'none');
$("#map").css('display', 'none');
$("#panel").css('display', 'none');
$("#load").css('display', 'none');
$("#googleMap").css('display', 'block');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
setLocationValue(position.coords.latitude,position.coords.longitude);
//getCurrentLocationValue(position.coords.latitude,position.coords.longitude);
var mapProp = {
center:new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
zoom:10,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var myMarker = new google.maps.Marker({
position: {lat:position.coords.latitude, lng:position.coords.longitude},
animation:google.maps.Animation.BOUNCE
});
myMarker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"You are Located in Lat: "+position.coords.latitude+' Lng: '+position.coords.longitude
});
infowindow.open(map,myMarker);
getNearby(position.coords.latitude,position.coords.longitude,map);
<?php /*?>$("#myNearby a").click(function(){
//alert('Working');
var request = {
location: {lat:position.coords.latitude, lng:position.coords.longitude},
radius: 5500,
types: [$("#location").val()]
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
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(place.name);
infowindow.open(map, this);
});
}
});<?php */?>
}
function setLocationValue(lat,lng){
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
//console.log(results);
$.each(arrAddress, function(i, address_component) {
if (address_component.types[0] == "locality") {
itemLocality = address_component.address_components[0].long_name;
//console.log("City: " + address_component.address_components[0].long_name + itemLocality);
$("#location").val(itemLocality);
}
});
}
else{
alert("No results found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
});
}
Remove the existing markers from the map before showing the new ones. Make the markers array global, then do this at the beginning of getNearby:
for (var i=0; i<markers.length; i++) {
markers[i].setMap(null);
}
markers = [];

Can someone tell me why I can see an InfoWindow when I click on an map marker?

Here is my code that will pull data from mysql and display the markers on the map. But I cant get the info windows to show when I click on a marker. Thank for any help.
The reference to the infowindows is at the very bottom on the page close to the end of the code after the ajax reference.
Thanks
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
function LoadMarkers(encodedString)
{
var bounds = new google.maps.LatLngBounds();
var stringArray = [];
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
addressDetails = stringArray[x].split("&&&");
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
var image = new google.maps.MarkerImage(addressDetails[3]);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: lat,
content: addressDetails[0]
});
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
info.open(map,this);
infos[0]=info;
});
bounds.extend(lat);
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(map);
}
}
}
map.fitBounds(bounds);
}
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = null;//new google.maps.Map(document.getElementById("map_canvas"), myOptions);
jQuery(document).ready( function($){
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
LoadMarkers(document.getElementById("encodedString").value);
setInterval(function () {
jQuery.ajax({
url:'ajaxload.php',
type: "POST",
data: {'refreshed':true},
success: function(data)
{
LoadMarkers(data);
}
});
}, 10000);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
The function LoadMarkers is defined in global scope, but the function closeInfos is defined locally inside the $.ready-callback.
Because of that the call of closeInfos() inside the click-handler of the marker fails and stops the further execution of the click-handler.
You must make closeInfos global accessible:
window.closeInfos=function(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}

Issue with google map API

I have to translate a google map api code from v2 to v3. I've tried but it is not working.
This is the old version code:
function getQueryVariable(variable){
var query = window.location.search.substring(1);
var vars=query.split("&");
for(var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address, year1,year2,year3) {
map = new GMap2(document.getElementById("map_canvas"));
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.getLatLng(address,function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 11);
var marker = new GMarker(point);
map.addOverlay(marker);
}
}
);
}
}
This is what I wrote:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(decodeURIComponent(pair[0]) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address) {
var map=new google.maps.Map(document.getElementById("map_canvas"));
geocoder = new google.maps.Geocoder();
geocoder.geocode(address, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var center = results[0].geometry.location;
map.setCenter(center);
var marker = new google.maps.Marker({
map: map,
position: center
});
}
}
}
Someone can tell me what I'm doing wrong?
Thanks a lot.
Marcello
There are syntax errors in your code. But the main issue is you need to initialize the google.maps.Map object. Currently there are 3 required options in the google.maps.MapOptions object:
https://developers.google.com/maps/documentation/javascript/reference#MapOptions
center | LatLng | The initial Map center. Required.
mapTypeId | MapTypeId | The initial Map mapTypeId. Required.
zoom | number | The initial Map zoom level. Required.
This works for me:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(decodeURIComponent(pair[0])) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address) {
var map=new google.maps.Map(document.getElementById("map_canvas"),{center:new google.maps.LatLng(0,0), zoom:2, mapTypeId : google.maps.MapTypeId.ROADMAP});
geocoder = new google.maps.Geocoder();
geocoder.geocode({address:address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var center = results[0].geometry.location;
map.setCenter(center);
if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport)
else if (results[0].geometry.bounds) map.fitBounds(results[0].geometry.bounds)
var marker = new google.maps.Marker({
map: map,
position: center
});
} else alert("Geocoder returns: " + status);
});
}
working example

Google Maps Directions dragged polyline coordinates reset after extending the route

Hey guys, the function of this code is described below.
there are some predefined functions below i.e getMapOption and others
function initialize(){
var divCalcDis = $('divCalcDis');
var pdist = $('pdist');
var pTimeTaken = $('pTimeTaken');
var txtLatLon = $('divLatLon');
var lblDistance = $('lblDistance');
var mapOption = mapHandler.getMapOption(that.LonLatCoordinates[0], 15, "Default");
map = mapHandler.getMap('map_canvas', mapOption);
var renderOption = { draggable: true };
directionsDisplay = new google.maps.DirectionsRenderer(renderOption);
directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () { for (i = 0; i < directionsDisplay.directions.routes.length; i++) {
//getting latlon
txtLatLon.innerHTML = "";
console.log(directionsDisplay.directions.routes[i].overview_path.length);
var latLng = directionsDisplay.directions.routes[i].overview_path[k];
var latLng = directionsDisplay.directions.routes[i].overview_path[directionsDisplay.directions.routes[i].overview_path.length - 1].toString();
latLng = latLng.split('(')[1];
latLng = latLng.split(')')[0];
latLng = latLng.split(' ');
latLng = latLng[0] + latLng[1];
txtLatLon.innerHTML += latLng;
}
});
startMap();
}
function startMap() {
var i=0;
google.maps.event.addListener(map, 'click', function (event) {
i++;
if(i === 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
that.origin = event.latLng; //comma seperated values of lat,lon
}
else if(i > 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
if (i === 2) {
that.dest = event.latLng; //comma seperated values of lat,lon
}
else if (i > 2) {
that.wayPTs.push({
location: that.dest,
stopover: true
});
that.dest = event.latLng;
}
that.calcRoute();
}});
};
function calcRoute() {
var divCalcDis = stringHandler._id('divCalcDis');
var pdist = stringHandler._id('pdist');
var pTimeTaken = stringHandler._id('pTimeTaken');
var txtLatLon = stringHandler._id('divLatLon');
txtLatLon.innerHTML = "";
if (!that.wayPTs.length > 1) {
this.wayPTs = null;
}
var request = this.directionsRequest(this.origin,this.dest,google.maps.DirectionsTravelMode.DRIVING,this.wayPTs,false,true,true,google.maps.DirectionsUnitSystem.METRIC);
that.directionsResponse.route(request, function (response, status) {
//console.log(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
};
**
I am making a project using Google Maps API V3 Directions library in which i am creating a route when a user click some place on the map
Here is a screenshot**
Now when i drag the direction drawn line it works smoothly and giving me the latitude and longitude correctly.
Here is a screenshot
But the Problem is when i click on anyother place on the map(after dragging) the waypoint refreshes and i get the old without drag route with the next stop as you can see below
Here is a Screenshot
How to save the latLon of the waypoint so they are available after creation of new points Thx
You need to push the coordinates into the route array so they will always be available. So push when you drag and push when you click. May be this can be of assistance to you. Best of luck.

Removing Google Map markers from Map was working, now its not

As i am working on object oriented javascript, i have created one map object and as i need to maintain the all previous routes and markers i am not creating new Map object. My code is as follows
function map() {
this.defaultMapOption = {
center : new google.maps.LatLng(0, 0),
zoom : 1,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
this.map = null;
this.marker = [];
this.directionsDisplay = null;
}
map.prototype.init = function() {
this.map = new google.maps.Map(document.getElementById("map"), this.defaultMapOption);
var map1 = this.map;
var marker1 = this.marker;
var count = 0;
google.maps.event.addListener(this.map, 'click', function(event) {
count++;
$(".tabNavigation li").find("a[href=markers]").trigger('click');
if ( marker1[count] ) {
marker1[count].setPosition(event.latLng);
}
else
{
marker1[count] = new google.maps.Marker({
position: event.latLng,
map: map1,
draggable : true
});
//by clicking double click on marker, marker must be removed.
google.maps.event.addListener(map.marker[count], "dblclick", function() {
console.log(map.marker);
map.marker[count].setMap(null);//this was working previously
map.marker[count].setVisible(false);//added this today
$("#markers ul li[rel='"+count+"']").remove();
});
google.maps.event.addListener(marker1[count], "dragend", function(innerEvent) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': innerEvent.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.addMarkerData(results, count);
}
else
{
alert("Geocoder failed due to: " + status);
}
});
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.addMarkerData(results, count);
}
else
{
alert("Geocoder failed due to: " + status);
}
});
}
});
}
Only above code works for only one marker. Means first time marker get removed on double click. After that it wont work.
Any ideas that why its stopped working!
Your count value is incrementing with new markers and in addListener(map.marker[count],...) , count will contain the latest value. So only that marker will be deleted.
So you should be decrementing the count value at the end in the addListener function.
You're adding marker[1] but then you try to remove marker[0]. Move your count++; from the beginning to the end of the function.