How can I add multiple searchBoxes in my google maps api web? - javascript

I'm trying to make a origin and destination menu, so the user will choose the locations in each input, and each input will add a marker to the map and then it will calculate the distance, this is my progress so far: I've successfully added a map with a search box, but I can't create another one and I don't know how to do this.
This is my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
<div style="background-color: #FFC012">
<input type="text" id="orign" placeholder="origin">
<input type="text" id="destn" placeholder="destination">
<br>
<div id="map-canvas">
<script>
var map = new google.maps.Map(document.getElementById('map-canvas'),{
center:{
lat: 19.4978,
lng: -99.1269
},
zoom:15
});
var marker = new google.maps.Marker({
map:map,
draggable: false
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
/*marker.setPosition(initialLocation); */
});
}
var searchBox = new google.maps.places.SearchBox(document.getElementById('orign'));
google.maps.event.addListener(searchBox, 'places_changed',function(){
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for(i=0; place=places[i];i++){
bounds.extend(place.geometry.location);
marker.setPosition(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
})
</script>
</div>
</div>

One option would be to start from the Autocomplete Directions Example in the documentation, change the Autocomplete objects to SearchBox objects, and the associated code to account for the differences (SearchBox has a places_changed event, Autocomplete has place_changed (singular); the routine to get the results also has a different name (singular vs. plural).
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
this.directionsRenderer.setMap(map);
var originInput = document.getElementById('orign');
var destinationInput = document.getElementById('destn');
var originAutocomplete = new google.maps.places.SearchBox(originInput);
var destinationAutocomplete =
new google.maps.places.SearchBox(destinationInput);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('places_changed', function() {
var places = autocomplete.getPlaces();
var place = places[0];
if (!place.place_id) {
window.alert('Please select an option from the dropdown list.');
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
Add a function to calculate the length of the returned route (from the question: Google Maps API: Total distance with waypoints):
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
proof of concept fiddle
code snippet:
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script
// src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 19.4978,
lng: -99.1269
},
zoom: 15
});
var marker = new google.maps.Marker({
map: map,
draggable: false
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
/*marker.setPosition(initialLocation); */
});
}
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
this.directionsRenderer.setMap(map);
var originInput = document.getElementById('orign');
var destinationInput = document.getElementById('destn');
var originAutocomplete = new google.maps.places.SearchBox(originInput);
var destinationAutocomplete =
new google.maps.places.SearchBox(destinationInput);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('places_changed', function() {
var places = autocomplete.getPlaces();
var place = places[0];
if (!place.place_id) {
window.alert('Please select an option from the dropdown list.');
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode
},
function(response, status) {
if (status === 'OK') {
me.directionsRenderer.setDirections(response);
computeTotalDistance(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
// from Google Maps API: Total distance with waypoints
// https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map-canvas {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div style="background-color: #FFC012; height:100%; width:100%;">
<input type="text" id="orign" placeholder="origin" value="Lindavista Vallejo III Secc">
<input type="text" id="destn" placeholder="destination" value="Lienzo Charro de La Villa">
<div id="total"></div>
<br>
<div id="map-canvas"></div>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>

Related

set google origin search box address with a variable

I'm trying to make origin SearchBox destination be string with legit direction, but when I do so I still need to select the first option for it to work (to calculate distance).
Got the this searching around to calculate distance between 2 points and it works perfectly:
How can I add multiple searchBoxes in my google maps api web?
I got a string for example :albrook mall which i know exist( this string is dynamic is coming from a variable and all address are validated. get the needed address pass it to a variable so I can read it on the frontEnd, and set the value of search box in the html. the value is updated with jquery
But what happens is that I still have to click on the origin search box then this list all possible locations which in my case is the first one, how can I make the map either auto select the first option or recognize the address that is set in the input value?
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 9.0271554,
lng: 79.4816371
},
zoom: 15
});
var marker = new google.maps.Marker({
map: map,
draggable: false
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
/*marker.setPosition(initialLocation); */
});
}
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
this.avoidTolls = true;
this.avoidHighways= true;
//this.provideRouteAlternatives= true,
this.avoidFerries= true;
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
this.directionsRenderer.setMap(map);
var originInput = document.getElementById('orign');
var destinationInput = document.getElementById('destn');
var originAutocomplete = new google.maps.places.SearchBox(originInput);
var destinationAutocomplete =
new google.maps.places.SearchBox(destinationInput);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('places_changed', function() {
var places = autocomplete.getPlaces();
var place = places[0];
if (!place.place_id) {
window.alert('Please select an option from the dropdown list.');
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode,
avoidTolls: this.avoidTolls
},
function(response, status) {
if (status === 'OK') {
me.directionsRenderer.setDirections(response);
computeTotalDistance(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
// from Google Maps API: Total distance with waypoints
// https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
time = (totalTime / 60).toFixed(2)
document.getElementById("totalkm").innerHTML ="" + totalDist + "km" ;
document.getElementById("totaltime").innerHTML ="" + time + " minutos";
if(totalDist <= 5){
document.getElementById("totalCost").innerHTML =" $3.50";
}
else{
kmPrice = (totalDist - 5) * 0.75;
document.getElementById("totalCost").innerHTML ="$" +(kmPrice + 3.50).toFixed(2)+ "";
}
}
function send_handle(){
let name=document.getElementById("name").value;
///let lastname= document.getElementById("lastname").value;
let inst= document.getElementById("instructions").value;
let origin= document.querySelector(".selectButtons input#orign").value;
let destination= document.querySelector(".selectButtons input#destn").value;
let cost= document.getElementById("totalCost").innerHTML;
let distance= document.getElementById("totalkm").innerHTML;
// win.focus();
}
</script>
<html>
<div class="selectButtons" >
<input type="text" id="orign" placeholder="origen">
<input type="text" id="destn" placeholder="destino">
<span> Distancia en KM <div id="totalkm">0km</div> </span>
<span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
<span> costo por envio<div id="totalCost">$0</div></div> </span>
</div>
</html>
You can call the places service to get the PlaceId (with your string), then pass that placeId into the constructor for your AutocompleteDirectionsHandler or if you already have the PlaceId (you are allowed to store those), just use it, although you probably want to initialize the origin input with the string.
var origin = "Allbrook, Panama";
var originInput = document.getElementById('orign');
originInput.value = origin;
const request = {
query: origin,
fields: ["name", "geometry", "place_id"],
};
var originPlaceId;
var service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK && results) {
originPlaceId = results[0].place_id;
console.log("placeId="+originPlaceId+" coords="+results[0].geometry.location.toUrlValue(6));
new AutocompleteDirectionsHandler(map, originPlaceId);
map.setCenter(results[0].geometry.location);
}
});
Add the initial origin placeId to the AutocompleteDirectionsHandler constructor:
function AutocompleteDirectionsHandler(map, originPlaceId) {
this.map = map;
this.originPlaceId = originPlaceId;
// ...
on load:
after selecting destination from dropdown:
code snippet:
let map;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 9.0271554,
lng: 79.4816371
},
zoom: 15
});
var origin = "Allbrook, Panama";
var originInput = document.getElementById('orign');
originInput.value = origin;
const request = {
query: origin,
fields: ["name", "geometry", "place_id"],
};
var originPlaceId;
var service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK && results) {
originPlaceId = results[0].place_id;
console.log("placeId="+originPlaceId+" coords="+results[0].geometry.location.toUrlValue(6));
new AutocompleteDirectionsHandler(map, originPlaceId);
map.setCenter(results[0].geometry.location);
}
});
var marker = new google.maps.Marker({
map: map,
draggable: false
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
/*marker.setPosition(initialLocation); */
});
}
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map, originPlaceId) {
this.map = map;
this.originPlaceId = originPlaceId;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
this.avoidTolls = true;
this.avoidHighways = true;
//this.provideRouteAlternatives= true,
this.avoidFerries = true;
this.directionsService = new google.maps.DirectionsService();
this.directionsRenderer = new google.maps.DirectionsRenderer();
this.directionsRenderer.setMap(map);
var originInput = document.getElementById('orign');
var destinationInput = document.getElementById('destn');
var originAutocomplete = new google.maps.places.SearchBox(originInput);
var destinationAutocomplete =
new google.maps.places.SearchBox(destinationInput);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('places_changed', function() {
var places = autocomplete.getPlaces();
var place = places[0];
if (!place.place_id) {
window.alert('Please select an option from the dropdown list.');
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode,
avoidTolls: this.avoidTolls
},
function(response, status) {
if (status === 'OK') {
me.directionsRenderer.setDirections(response);
computeTotalDistance(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
// from Google Maps API: Total distance with waypoints
// https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
time = (totalTime / 60).toFixed(2)
document.getElementById("totalkm").innerHTML = "" + totalDist + "km";
document.getElementById("totaltime").innerHTML = "" + time + " minutos";
if (totalDist <= 5) {
document.getElementById("totalCost").innerHTML = " $3.50";
} else {
kmPrice = (totalDist - 5) * 0.75;
document.getElementById("totalCost").innerHTML = "$" + (kmPrice + 3.50).toFixed(2) + "";
}
}
function send_handle() {
let name = document.getElementById("name").value;
///let lastname= document.getElementById("lastname").value;
let inst = document.getElementById("instructions").value;
let origin = document.querySelector(".selectButtons input#orign").value;
let destination = document.querySelector(".selectButtons input#destn").value;
let cost = document.getElementById("totalCost").innerHTML;
let distance = document.getElementById("totalkm").innerHTML;
// win.focus();
}
function createMarker(place) {
if (!place.geometry || !place.geometry.location) return;
const marker = new google.maps.Marker({
map,
position: place.geometry.location,
});
google.maps.event.addListener(marker, "click", () => {
infowindow.setContent(place.name || "");
infowindow.open(map);
});
}
window.initMap = initMap;
#map-canvas {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<html>
<div class="selectButtons">
<input type="text" id="orign" placeholder="origen" />
<input type="text" id="destn" placeholder="destino" />
<span> Distancia en KM <div id="totalkm">0km</div> </span>
<span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
<span> costo por envio<div id="totalCost">$0</div> </span>
</div>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>
</html>

Javascript find location with lat,long and radius

I need to find all the locations near by the lat long and radius provided.I think I can achieve this by using geofence but I don't know how to proceed.I have the following data.
set of lat long and to get the location for radius within 5km for all the lat long by each.
Any one help how to start this.
Inputs I have:
lat long
33.450909, -112.073196
33.466210, -112.064620
33.451640, -112.099130
33.437160, -112.048400
33.480860, -112.082130
33.489950, -112.074700
Tried so far:
<!DOCTYPE html >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Creating a Store Locator on Google Maps</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body style="margin:0px; padding:0px;" onload="initMap()">
<div>
<label for="raddressInput">Search location:</label>
<input type="text" id="addressInput" size="15"/>
<label for="radiusSelect">Radius:</label>
<select id="radiusSelect" label="Radius">
<option value="50" selected>50 kms</option>
<option value="30">30 kms</option>
<option value="20">20 kms</option>
<option value="10">10 kms</option>
</select>
<input type="button" id="searchButton" value="Search"/>
</div>
<div><select id="locationSelect" style="width: 10%; visibility: hidden"></select></div>
<div id="map" style="width: 100%; height: 90%"></div>
<script>
var map;
var markers = [];
var infoWindow;
var locationSelect;
function initMap() {
var sydney = {lat: 33.450909, lng: -112.073196};
map = new google.maps.Map(document.getElementById('map'), {
center: sydney,
zoom: 11,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
searchButton = document.getElementById("searchButton").onclick = searchLocations;
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'storelocator.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var id = markerNodes[i].getAttribute("id");
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name;
locationSelect.appendChild(option);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAVD0ngfhOFs5rnww7UFyz9rN6UznOIZ1U&callback=initMap">
</script>
</body>
</html>
Using the above I can able to point single point,But what I want is to get the location around each lat long provided above radius is 5 km
If you are already using Google Maps, then I think you can try with computeDistanceBetween.
This is a short example of how to use it. You just need to eliminate those distances greater than the radius you set.
var home = ['Store', new google.maps.LatLng(29.520130, -98.415542)];
var pts = [
['Client A', new google.maps.LatLng(29.5197902, -98.3867079)],
['Client B', new google.maps.LatLng(29.5165967, -98.4235714)],
['Client C', new google.maps.LatLng(29.5198805, -98.3676648)]
];
var dist = google.maps.geometry.spherical.computeDistanceBetween;
pts.forEach(function(pt) {
console.log(home[0] + ' to ' + pt[0] + ': ' + (dist(home[1], pt[1])).toFixed(10));
});

google maps autocomplete with dynamic arrays

So I have dynamic text inputs which i require to give it access to google maps (places) autocomplete api.
The "start", "end" and 1st "waypoint"(not dynamic) works well, but after 4 hours, i am still struggling to get my dynamic text inputs to autocomplete. And can not find anything resembling the answer on google.
This is what i have so far:
Javascript:
function initialize() {
var options = {
componentRestrictions: {
country: "au"
}
};
var inputs = document.getElementById('start');
var autocompletes = new google.maps.places.Autocomplete(inputs, options);
var inpute = document.getElementById('end');
var autocompletee = new google.maps.places.Autocomplete(inpute, options);
var waypoints = document.getElementsByName("waypoints[]");
for (var i = 0; i < waypoints.length; i++) {
var inputw = waypoints[i];
var autocompletew = new google.maps.places.Autocomplete(inputw, options);
}
directionsDisplay = new google.maps.DirectionsRenderer();
var melbourne = new google.maps.LatLng(-31.953512, 115.857048);
var myOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: melbourne
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
HTML:
var counter = 1;
var limit = 10;
var i = 1;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = (counter + 1) + "<input type=text name=waypoints[] autocomplete=on>";
document.getElementById(divName).appendChild(newdiv);
counter++;
i++;
var inputw = waypoints[i];
var autocompletew = new google.maps.places.Autocomplete(inputw, options);
}
}
Dynamically creating the content, then using the reference to that works for me:
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newbr = document.createElement('br');
var newtxt = document.createTextNode(""+(counter+1));
var newinput = document.createElement("input");
newinput.setAttribute("name","waypoints[]");
newinput.setAttribute("autocompute","on");
newinput.setAttribute("type", "text");
document.getElementById(divName).appendChild(newbr);
document.getElementById(divName).appendChild(newtxt);
document.getElementById(divName).appendChild(newinput);
counter++;
i++;
var autocompletew = new google.maps.places.Autocomplete(newinput, ACoptions);
}
proof of concept fiddle
code snippet:
var counter = 1;
var limit = 10;
var i = 0;
var ACoptions = {
componentRestrictions: {
country: "au"
}
};
function initialize() {
var inputs = document.getElementById('start');
var autocompletes = new google.maps.places.Autocomplete(inputs, ACoptions);
var inpute = document.getElementById('end');
var autocompletee = new google.maps.places.Autocomplete(inpute, ACoptions);
var waypoints = document.getElementsByName("waypoints[]");
for (var i = 0; i < waypoints.length; i++) {
var inputw = waypoints[i];
var autocompletew = new google.maps.places.Autocomplete(inputw, ACoptions);
}
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
var melbourne = new google.maps.LatLng(-31.953512, 115.857048);
var myOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: melbourne
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
google.maps.event.addDomListener(document.getElementById('getdir'), 'click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
google.maps.event.addDomListener(window, "load", initialize);
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newbr = document.createElement('br');
var newtxt = document.createTextNode("" + (counter + 1));
var newinput = document.createElement("input");
newinput.setAttribute("name", "waypoints[]");
newinput.setAttribute("autocompute", "on");
newinput.setAttribute("type", "text");
// newin = (counter + 1) + "<input type=text name=waypoints[] autocomplete=on>";
document.getElementById(divName).appendChild(newbr);
document.getElementById(divName).appendChild(newtxt);
document.getElementById(divName).appendChild(newinput);
counter++;
i++;
console.log("cntr=" + counter + " i=" + i + " waypoints[].length=" + document.getElementsByName("waypoints[]"));
// var inputw = waypoints[i];
var autocompletew = new google.maps.places.Autocomplete(newinput, ACoptions);
}
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var checkboxArray = document.getElementById('dynamicInput');
var waypointElmts = document.getElementsByName('waypoints[]');
for (var i = 0; i < waypointElmts.length; i++) {
if (waypointElmts[i].value.length > 0) {
waypts.push({
location: waypointElmts[i].value,
stopover: true
});
}
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>
<input id="start" value="Margaret River, AU" />
<input id="end" value="Perth, AU" />
<div id="dynamicInput">
<br>1
<input type="text" name="waypoints[]" autocomplete="on">
</div>
<input type="button" value="Another Delivery" onClick="addInput('dynamicInput');">
<input id="getdir" type="button" value="get route" />
<div id="map_canvas"></div>

Duplicate values in google map pagination

The code below display a map and display the results in UL. I have 2 buttons that display train station and shopping mall.Initially, it will display the results correctly but If I click the other button, it will display duplicate values.
Javascript
var map;
var pos;
var distance;
var distancearray = [];
var markers = [];
//=================================================================
function initialize() {
googleMapsLoaded = false;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13
});
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var request = {
location:pos,
radius:3000, //3000 Meters
type:initialtype
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'You Are Here',
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function callback(results, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
else{
for (var i = 0; i < results.length; i++)
markers.push(createMarker(results[i]));
}
} //end callback function
/* listen to the tilesloaded event
if that is triggered, google maps is loaded successfully for sure */
google.maps.event.addListener(map, 'tilesloaded', function() {
googleMapsLoaded = true;
// document.getElementById("mapnotification").innerHTML = "Map Loaded!";
$("#mapnotification").hide();
$("#map-loaded").show();
$("#map-loaded").css('visibility', 'hidden');
$("#map-notloaded").hide();
//clear the listener, we only need it once
google.maps.event.clearListeners(map, 'tilesloaded');
});
setTimeout(function() {
if (!googleMapsLoaded) {
//we have waited 7 secs, google maps is not loaded yet
document.getElementById("mapnotification").innerHTML = "Map NOT Loaded! Make sure you have stable internet connnection";
$("#mapnotification").hide();
$("#map-notloaded").show();
$("#map-loaded").hide();
}
}, 7000);
function createMarker(place) { // Create Marker and the Icon of the marker
// var bounds = new google.maps.LatLngBounds();
var markerlat;
var markerlon;
var p2;
var output="";
var placesList = document.getElementById('places');
placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8,
fillColor:'00a14b',
fillOpacity:0.3,
fillStroke: '00a14b',
strokeWeight:4,
strokeOpacity: 0.7
}, // end icon
}); //end of marker variable
markerlat = marker.getPosition().lat()
markerlon = marker.getPosition().lng()
console.log("Markers Lat" + markerlat);
console.log("Markers Lon" + markerlon );
p2 = new google.maps.LatLng(markerlat, markerlon);
distance = [calcDistance(pos, p2)];
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
distancearray.push([distance, place.name]);
distancearray.sort();
console.log("distancearraylength" + distancearray.length);
console.log("Summary" + distancearray);
for(var i = 0; i < distancearray.length; i++){
output += '<li>' + distancearray[i][1] + " " + distancearray[i][0]+ " " + "km" + '</li>';
placesList.innerHTML = output;
}
google.maps.event.addListener(marker, 'click', function() { //show place name when marker clicked
infowindow.setContent(place.name);
infowindow.open(map, marker);
}); // end of marker show place name
} // end createMarker function
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
} // End handleNoGeolocation function
} //End function initialize
//==========================================================================================================//
$(document).on('pagebeforeshow','#itemPanel2', function(e, data){ // Loading of Nearest Place Options
bindchoicesclick();
function bindchoicesclick(){
$("#subway_station").on("click",function(){
// alert("subway");
markers = [];
pos="";
while(distancearray.length > 0) {
distancearray.pop();
}
while(markers.length > 0) {
markers.pop();
}
//$("#places").empty();
initialtype = ['subway_station'];
buttonholder = "Nearest Station";
$("#find").val(buttonholder);
$("#find").button("refresh");
initialize();
});
$("#shopping_mall").on("click",function(){
// alert("stores");
markers = [];
pos="";
while(distancearray.length > 0) {
distancearray.pop();
}
while(markers.length > 0) {
markers.pop();
}
// distancearray.splice(0).
// $("#places").empty();
initialtype = ['shopping_mall'];
buttonholder = "Nearest Mall";
$("#find").val(buttonholder);
$("#find").button("refresh");
initialize();
});
}
});
HTML
<h1 id="headerField">Nearby Search</h1>
</div>
Search Nearest Train Station
Search Nearest Mall
</div>
<!--Train Stations -->
<div id="globa_map" data-role="page">
<div data-role="header">
Back
Refresh
<h1 id="headerField">Global</h1>
</div>
<div data-role="content">
<!-- <input type="button" id="refreshmap" value="Refresh"> -->
<p id="mapnotification">Please wait while the map is loading...</p>
<p id="map-loaded">Map Loaded!</p>
<p id="map-notloaded">Map NOT Loaded! Make sure you have stable internet connnection</p>
<h2>Results</h2>
<ul id="places"></ul>
<button id="more">More results</button>
<div id="map" style="height:400px;">
</div>
</div>

Permanent Google Map Infowindow

I have a marker which has a dynamic position (i.e. updated periodically). When marker is clicked, an infowindow is shown but when marker position is updated, the infowindow gets automatically closed. I want that when marker position is updated, infowindow position should also get updated automatically. How to solve this.
P.S. :- infowindow contain a form which is editable by the user.
Problem : when user is editing/filling the form and marker position gets updated (form not submitted yet), then the form will get closed and user will lose his data.
<script type="text/javascript">
var map;
var lat_longs = new Array();
var geocoder = null;
var infoWindow = new google.maps.InfoWindow();
var trafficLayer = null;
var weatherLayer = null;
var markers = new Array();
var poi = new Array();
var fitMap = 0;
loc_array = new Array();
totUpdateOld = new Array();
ident = 0;
function showMap() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng('-0.57128','117.202148'),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
geocoder = new google.maps.Geocoder();
trafficLayer = new google.maps.TrafficLayer();
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELCIUS
});
showCarPosition(function() {
fitMapToBounds();
});
}
function showCarPosition(){
if (markers.length>0){
ident = 2;
}
var car_icon;
jQuery.getJSON('<s:property value="jsonUrl"/>','', function(data) {
var arrayCar = data.listCar;
for (var i = 0; i < arrayCar.length; i++) {
var car = arrayCar[i];
var status = "";
var tanggal = "never";
var car_type = (car.type != "" || car.type != null)?' ('+car.type+')':'';
if(car.lastUpdate == null){
car_icon = ctx + 'web/img/car_black.png';
status = "Belum pernah kirim data";
}else if((not_active = (currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 30){ //diff in minute
car_icon = ctx + 'web/img/car_red.png';
status = convertMinute(not_active);
}else if((((currentdate - stringToDate(car.lastUpdate))/ 1000 / 60) >= 5) && (car.lastSpeed == 0)){ //diff in minute
car_icon = ctx + 'web/img/car_yellow.png';
status = "Berhenti";
}else
car_icon = ctx + 'web/img/car_green.png';
if(car.lastUpdate != null){
var splitDate = car.lastUpdate.split("T");
tanggal = splitDate[1]+" "+splitDate[0].split("-")[2]+"-"+bulan[parseInt(splitDate[0].split("-")[1])]+"-"+splitDate[0].split("-")[0];
}
var coordinate = new google.maps.LatLng(car.latitude, car.longitude);
var windowContent =[
'<div class="windowcontent"><ul class="nav infowindow nav-pills nav-stacked">',
'<li class="active">'+car.plate +car_type+' - '+ car.driverName +'</li>',
(status != null)?'<li>'+status+'</li>':'',
(car.phoneNumber != null)?'<li>Phone : ' + car.phoneNumber+ '</li>':'',
'<li>Last Temp : ' + car.lastTemp+ '</li>',
(parseInt(car.lastSpeed)>0)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
(car.type != "" || car.type != null)?'<li>Last Speed : ' + car.lastSpeed+ '</li>':'',
'<li>Last Connected : ' + tanggal+ '</li>',
'<li>'+((car.note != null)?car.note:'no notes')+'<li>',
'<div id="'+car.id+'"></div></ul>',
'<span id="'+car.id+'" onclick="editinfo(this, \''+car.note+'\');">Edit Note</span></div>']
.join('');
if (ident == 0){
var marker = createMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
});
loc_array[car.id] = i;
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}else{
if (car.totalUpdate > totUpdateOld[car.id]) {
var map_post = loc_array[car.id];
markers[map_post].setMap(null);
var marker = updateMarker({
map: map,
position: coordinate,
icon: car_icon,
labelContent: ((car.driverName == null)?car.plate:car.driverName)+'-'+car.lastSpeed,
labelAnchor: new google.maps.Point(32, 0),
labelClass: "unitlabel",
labelStyle: {opacity: 1.0}
}, map_post);
bindInfoWindow(marker, 'click', windowContent);
google.maps.event.addListener(infoWindow, 'domready', function(){
jQuery('.viewlog').click(function() {
jQuery.history.load(jQuery(this).attr('href'));
return false;
});
});
}
}
totUpdateOld[car.id] = car.totalUpdate;
}
fitMapToBounds();
});
setTimeout("showCarPosition()",5000);
}
function createMarker(markerOptions) {
var marker = new MarkerWithLabel(markerOptions);
markers.push(marker);
lat_longs.push(marker.getPosition());
return marker;
}
function updateMarker(markerOptions,id) {
var marker = new MarkerWithLabel(markerOptions);
markers[id] = marker;
lat_longs[id] = marker.getPosition();
return marker;
}
function fitMapToBounds() {
var bounds = new google.maps.LatLngBounds();
if (fitMap == 0){
if (lat_longs.length>0) {
for (var i=0; i<lat_longs.length; i++) {
bounds.extend(lat_longs[i]);
}
map.fitBounds(bounds);
fitMap = 1;
}
}
}
function bindInfoWindow(marker, event, windowContent) {
google.maps.event.addListener(marker, event, function() {
infoWindow.setContent(windowContent);
infoWindow.open(map, marker);
});
}
jQuery(document).ready(function() {
showMap();
});
</script>
<div id="map_canvas" class="widgettitle" style="height:540px;"></div>
call this function when the marker position is changed .
infowindow.open(map,marker);
Put an onblur event handler on the text field that calls a halt to the repositioning.
Then when it is submitted and goes to the new point, restart it (if needed).

Categories