I am trying to adapt this Google Maps distance calculator to my needs, but am not overly familiar with plain Javascript, and only Jquery.
I am trying to modify one of the destination variables so that it pulls it from a text box instead.
Usually the line reads :
var destinationA = 'pe219px';
But I am trying to change it to the following, usually I would do this with a keyup function to update the value as the person types in jquery, but im not sure what im doing in plain javascript. This is what I have come up with so far, but it doesn't appear to do a lot :
function setValue() {
destinationA=parseInt(document.getElementById('deliverypostcode').value);
}
This is the example I am trying to modify
https://developers.google.com/maps/documentation/javascript/examples/distance-matrix
This is the whole code :
<!DOCTYPE html>
<html>
<head>
<title>Distance Matrix service</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 50%;
}
#content-pane {
float:right;
width:48%;
padding-left: 2%;
}
#outputDiv {
font-size: 11px;
}
</style>
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = new google.maps.LatLng(53.003604, -0.532764);
var origin2 = 'pe219px';
function setValue() {
destinationA=parseInt(document.getElementById('deliverypostcode').value);
}
var destinationB = new google.maps.LatLng(53.003604, -0.532764);
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(53.003604, -0.532764),
zoom: 8
};
map = new google.maps.Map(document.getElementById('map-canvas'), opts);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="content-pane">
<div id="inputs">
<form name="form1" method="post" action="">
<label for="deliverypostcode">Your Postcode</label>
<input type="text" name="deliverypostcode" id="deliverypostcode">
</form>
<p><button type="button" onclick="calculateDistances();">Calculate
distances</button></p>
</div>
<div id="outputDiv"></div>
</div>
<div id="map-canvas"></div>
</body>
</html>
Your function setValue is never called.
What if you delete it and just place the following line at the begining of calculateDistances ?
var destinationA= document.getElementById('deliverypostcode').value;
This works for me. Also, you don't need to parseInt your text input. Geocoding converts strings to a lat/long coordinates.
Related
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));
});
this google map is to get directions to a location specified by coordinates of the customer as the destination.
To get that from data in the select, i make it a google.maps.LatLng object, and i save the coordinates as a string in the value, then i parse out the latitude and longitude to create the LatLng object.
the steps is :
1-save the coordinates in the option value:
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
2-parse those coordinates and create a google.maps.LatLng object in the directions request:
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
// ....
(all the above works fine)
-----This is where i am stuck:-----
Even the direction to a specified marker is displayed, the problem is that all markers still in the map,
for me I try to make my function display just two things the direction and the marker with the code-client whom I choose, and all other markers will hide.
Here is my Notes about what i add in my code,
**1--***Once I added this function to push all markers in one variable*
makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/3cce25789f00c1b84ccb5b231ec455b7/raw/393220f08a02b962e3e764d2b497b318353828db/gistfile1.txt', function(data) {
for (var i = 0; i < data.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].Latitude, data[i].Longitude),
title: data[i].CodeClient,
map: map
});
gmarkers.push(marker);
}
});
**2--***and i add this function to hide other markers*
function toggleMarkers() {
for (i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);
else gmarkers[i].setMap(map);
}
}
This problem I have been facing for days and can't seem to resolve , even I've tried looking at a large variety of code blocks here and on the Google Maps API documentation but STILL have not been able to figure out how to hide other markers.
Any suggestions, ideas and help will much appreciated!
this is a screenshot :
----------------------------------------------------------------------------------------------------------------------------------
Here is my code after i updated it
after your advises ,this the update of my code .
it work good , after i click on the button (clear markers) all markers will remove.
Now i wanna know how to make the function toggleMarkers() , remove all markers but it will keep the marker with the code-client whom I choose,
var gmarkers = [];
var map;
var directionsService;
var directionsDisplay;
var geocoder;
var infowindow;
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function init() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
/*++++++++++++++++++*/
var mapOptions = {
zoom: 6,
center: center = new google.maps.LatLng(32, -6),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
/*++++++++++++++++++*/
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions_panel'));
// Detect user location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': userLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('start').value = results[0].formatted_address
}
});
}, function() {
alert('Geolocation is supported, but it failed');
});
}
/*++++++++++++++++++*/
makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/3cce25789f00c1b84ccb5b231ec455b7/raw/393220f08a02b962e3e764d2b497b318353828db/gistfile1.txt', function(data) {
var data = JSON.parse(data.responseText);
var selectBox = document.getElementById('destination');
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
});
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function toggleMarkers() {
for (i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);
else gmarkers[i].setMap(map);
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function addOption(selectBox, text, value) {
var option = document.createElement("OPTION");
option.text = text;
option.value = value;
selectBox.options.add(option);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
var hakim = document.getElementById('destination');
console.log("selected option value=" + destination);
console.log(" value=" + hakim);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
var request = {
origin: start,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
console.log("origin:" + start);
console.log("dest:" + destination.toUrlValue(12));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
alert("???");
displayLocation(hakim);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function displayLocation(rythmstu_innotec) {
var content = '<div class="infoWindow"><strong> Code Client : ' + rythmstu_innotec.CodeClient + '</strong>' +
'<br />Latitude : ' + rythmstu_innotec.Latitude +
'<br />Longitude : ' + rythmstu_innotec.Longitude +
'<br />Route : ' + rythmstu_innotec.Route +
'<br />Secteur : ' + rythmstu_innotec.Secteur +
'<br />Agence : ' + rythmstu_innotec.Agence +
'<br />prenom de Client : ' + rythmstu_innotec.PrenomClient +
'<br />Num Adresse : ' + rythmstu_innotec.NumAdresse +
'<br />GeoAdresse : ' + rythmstu_innotec.GeoAdresse +
'<br />Téléphone : ' + rythmstu_innotec.Tel +
'<br />Whatsapp : ' + rythmstu_innotec.Whatsapp +
'<br />Nbr Frigos : ' + rythmstu_innotec.NbrFrigo +
'<br />Ouverture Matin : ' + rythmstu_innotec.OpenAm +
'<br />Fermeture Matin : ' + rythmstu_innotec.CloseAm +
'<br />Ouverture après-midi : ' + rythmstu_innotec.OpenPm +
'<br />Fermeture Après-midi : ' + rythmstu_innotec.ClosePm + '</div>';
if (parseInt(rythmstu_innotec.Latitude) == 0) {
geocoder.geocode({
'GeoAdresse': rythmstu_innotec.GeoAdresse
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.rythmstu_innotec,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: rythmstu_innotec.name
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
body {
font: normal 14px Verdana;
}
h1 {
font-size: 24px;
}
h2 {
font-size: 18px;
}
#sidebar {
float: right;
width: 30%;
}
#main {
padding-right: 15px;
}
.infoWindow {
width: 220px;
}
<title>MAP itinéraire </title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<body onload="init();">
<form id="services">
Location: <input type="text" id="start" value="Midar" /> Destination:
<select id="destination" onchange="calculateRoute();"></select>
<input type="button" value="clear map" onclick="toggleMarkers();" />
</form>
<section id="sidebar">
<div id="directions_panel"></div>
</section>
<section id="main">
<div id="map_canvas" style="width: 70%; height: 750px;"></div>
</section>
</body>
You never call the toggleMarkers function.
Modified it to be hideMarkers:
function hideMarkers() {
for (i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
}
Then call it in the directions service callback function on success:
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
var hakim = document.getElementById('destination');
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
var request = {
origin: start,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
hideMarkers(); // <========================= call it here
}
});
displayLocation(hakim);
}
code snippet:
var gmarkers = [];
var map;
var directionsService;
var directionsDisplay;
var geocoder;
var infowindow;
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function init() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
/*++++++++++++++++++*/
var mapOptions = {
zoom: 6,
center: center = new google.maps.LatLng(32, -6),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
/*++++++++++++++++++*/
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions_panel'));
// Detect user location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': userLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('start').value = results[0].formatted_address
}
});
}, function() {
alert('Geolocation is supported, but it failed');
});
}
/*++++++++++++++++++*/
makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/3cce25789f00c1b84ccb5b231ec455b7/raw/393220f08a02b962e3e764d2b497b318353828db/gistfile1.txt', function(data) {
var data = JSON.parse(data.responseText);
var selectBox = document.getElementById('destination');
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
});
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function hideMarkers() {
console.log("gmarkers.length=" + gmarkers.length);
for (i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function addOption(selectBox, text, value) {
var option = document.createElement("OPTION");
option.text = text;
option.value = value;
selectBox.options.add(option);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
var hakim = document.getElementById('destination');
console.log("selected option value=" + destination);
console.log(" value=" + hakim);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
var request = {
origin: start,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
console.log("origin:" + start);
console.log("dest:" + destination.toUrlValue(12));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
hideMarkers();
}
});
displayLocation(hakim);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function displayLocation(rythmstu_innotec) {
var content = '<div class="infoWindow"><strong> Code Client : ' + rythmstu_innotec.CodeClient + '</strong>' +
'<br />Latitude : ' + rythmstu_innotec.Latitude +
'<br />Longitude : ' + rythmstu_innotec.Longitude +
'<br />Route : ' + rythmstu_innotec.Route +
'<br />Secteur : ' + rythmstu_innotec.Secteur +
'<br />Agence : ' + rythmstu_innotec.Agence +
'<br />prenom de Client : ' + rythmstu_innotec.PrenomClient +
'<br />Num Adresse : ' + rythmstu_innotec.NumAdresse +
'<br />GeoAdresse : ' + rythmstu_innotec.GeoAdresse +
'<br />Téléphone : ' + rythmstu_innotec.Tel +
'<br />Whatsapp : ' + rythmstu_innotec.Whatsapp +
'<br />Nbr Frigos : ' + rythmstu_innotec.NbrFrigo +
'<br />Ouverture Matin : ' + rythmstu_innotec.OpenAm +
'<br />Fermeture Matin : ' + rythmstu_innotec.CloseAm +
'<br />Ouverture après-midi : ' + rythmstu_innotec.OpenPm +
'<br />Fermeture Après-midi : ' + rythmstu_innotec.ClosePm + '</div>';
if (parseInt(rythmstu_innotec.Latitude) == 0) {
geocoder.geocode({
'GeoAdresse': rythmstu_innotec.GeoAdresse
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.rythmstu_innotec,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: rythmstu_innotec.name
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
body {
font: normal 14px Verdana;
}
h1 {
font-size: 24px;
}
h2 {
font-size: 18px;
}
#sidebar {
float: right;
width: 30%;
}
#main {
padding-right: 15px;
}
.infoWindow {
width: 220px;
}
<title>MAP itinéraire </title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<body onload="init();">
<form id="services">
Location: <input type="text" id="start" value="Midar" /> Destination:
<select id="destination" onchange="calculateRoute();"></select>
<input type="button" value="clear map" onclick="toggleMarkers();" />
</form>
<section id="sidebar">
<div id="directions_panel"></div>
</section>
<section id="main">
<div id="map_canvas" style="width: 70%; height: 750px;"></div>
</section>
</body>
You do not need to use var marker = new google.maps.Marker for the Directions API. They are automatically added there and will also automatically disappear once you request for a new route.
Here is a sample app that renders the directions once the dropdown menu is changed. You can see the Javascript codes that it does not have anything that calls the marker or infowindow object, but they are both present in the map. The marker is automatically added on the origin and destination point. And if you click on those markers, the infowindow automatically appears!
function initMap() {
var directionsService = new google.maps.DirectionsService();
var chicago = new google.maps.LatLng(41.85, -87.65);
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('distance-map'), {
zoom: 5.2,
center: chicago
});
directionsDisplay.setMap(map);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
#distance-map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#warnings-panel {
width: 100%;
height:10%;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<br />
<div id="distance-panel">
Start:
<select id="start">
<option value='41.878114,-87.629798'>Chicago</option>
<option value='42.331427,-83.045754'>Detroit</option>
<option value='39.099727,-94.578567'>Kansas City</option>
<option value='41.600545,-93.609106'>Des Molines</option>
</select>
End:
<select id="end">
<option value='38.833882,-104.821363'>Colorado Springs</option>
<option value='36.162664,-86.781602'>Nashville</option>
<option value='39.768403,-86.158068'>Indianapolis</option>
<option value='36.162664,-86.781602'>Nashville</option>
</select>
</div>
<br />
<div id="distance-map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDLHKWYAEE2PDjvt6BaBH1SIs4Q93PMpQs&callback=initMap">
</script>
</body>
</html>
You may also check the jsbin version
here.
Hope this answered your question.
This is my code, When i am calling removeMarkers(), it's not removing the markers.
function receiver(data, textStatus, XMLHttpRequest) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var lat = json[i]["lat"];
var lng = json[i]["lng"];
// push object into features array
features.push({ position: new google.maps.LatLng(lat,lng) });
}
features.forEach(function(feature) {
var marker1 = new google.maps.Marker({
position: feature.position,
//icon: icons[feature.type].icon,
map: map
});
});
gmarkers.push(marker1);
}
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
This is my full code. For displaying places(church) that which i saved in my database along the route from origin to destination. If i changed the origin and destination i want to remove old markers and displaying new markers without refreshing the page.
css
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
html
<div id="map" height="460px" width="100%"></div>
<input type="text" id="distance" value="3" size="2">
<input type="text" id="from" />to
<input type="text" id="to" />
<input type="submit" onClick="route()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=api_ key&libraries=places"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/routeboxer/src/RouteBoxer.js" type="text/javascript"></script>
javascript
<script>
var map;
var marker;
var infowindow;
var messagewindow;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var boxes = null;
var coordinates=null;
var features = [];
var gmarkers = [];
<?php
echo "
var lat={$lat};
var lng={$lng};
"
?>
function initialize() {
var location = {lat: 10.525956868983068, lng:76.21387481689453};
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 13
});
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({
map: map
});
}
function route() {
removeMarkers()
clearBoxes();
distance = parseFloat(document.getElementById("distance").value) * 0.1;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
var path = result.routes[0].overview_path;
boxes = routeBoxer.box(path, distance);
drawBoxes();
findPlaces(0);
} else {
alert("Directions query failed: " + status);
}
});
}
function drawBoxes() {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 0,
map: map
});
}
}
function findPlaces(searchIndex) {
var request = {
bounds: boxes[searchIndex],
};
coordinates = boxes[searchIndex].toString().match(/[0-9]+\.[0-9]+/g);
$.ajax({
url:"http://localhost/church_finder/index.php/MapController/search_church",
type:'POST',
data:{coordinates:coordinates},
//dataType:'json',
success: receiver
});
if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
searchIndex++;
if (searchIndex < boxes.length)
findPlaces(searchIndex);
} else {
setTimeout("findPlaces(" + searchIndex + ")", 1000);
}
}
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
function receiver(data, textStatus, XMLHttpRequest) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var lat = json[i]["lat"];
var lng = json[i]["lng"];
features.push({ position: new google.maps.LatLng(lat,lng) });
}
features.forEach(function(feature) {
var marker1 = new google.maps.Marker({
position: feature.position,
map: map
});
});
gmarkers.push(marker1);
}
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
enter image description here
function removeMarkers(){
features.length=0;
if (gmarkers != []) {
for(var i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
gmarkers =[];
}
Your app throws loads of errors in the console and this is just a temporary fix to what you are asking for:
change the origin and destination, I want to remove old markers and
displaying new markers without refreshing the page
call your initialize() function with a script tag in your HTML file. This is where you include your API key for the project:
<script defer async src="https://maps.googleapis.com/maps/api/js?
key=YOUR_KEY&callback=initialize">
Where is the map element passed in the map constructor?
Create a div element in your HTML to contain the map and add CSS style to it
#map {
height: 100%;
}
html, body {
margin: 0;
padding: 0;
height: 100%;
}
This is actually in the Google Maps API documentation;
Always set the map height explicitly to define the size of the div
element that contains the map.
Now into your JS code...
What are you using var service for? var service is firstly declared in the global scope with a null value and then assigned to a PlacesService constructor...but service is not defined simply because you have not included the places library in your script tag:
ADD PLACES LIBRARY IF YOU WANT TO USE PLACES API
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?
key=YOUR_API_KEY&_ADD_libraries=places_PLEASE_"></script>
Because var service cannot be run, just remove it (it actually does not do anything but adding lines in your code right now) along with the RouteBoxer()
REMOVE THESE LINES - THEY ARE USELESS RIGHT NOW
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
If you do this, without refreshing the page, you clear the markers for each subsequent requests. You get loads of errors still because you have both syntax and logic bugs in your app.
Get a BIN here
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been researching this all day and still haven't come across a solution that works. I'm using the Google Maps Distance Matrix Service with 1 origin and 14 destinations. I modified the sample code from Google (https://developers.google.com/maps/documentation/javascript/examples/distance-matrix) and just added more destinations to test it out. With anything over 10 destinations, the OVER_QUERY_LIMIT error occurs and mis-places a marker.
From the usage limits I found (100 elements per 10 seconds), I shouldn't be hitting the limit at all. I have also tried inserting my API Key in this line, to no avail:
src="https://maps.googleapis.com/maps/api/js?v=3.exp"
Any help would be appreciated! Thanks.
Code changes to the sample code from Google:
var destinationA = new google.maps.LatLng(45.465422,9.185924);
var destinationB = new google.maps.LatLng(41.385064,2.173403);
var destinationC = new google.maps.LatLng(40.416775,-3.70379);
var destinationD = new google.maps.LatLng(51.507351,-0.127758);
var destinationE = new google.maps.LatLng(48.856614,2.352222);
var destinationF = new google.maps.LatLng(41.902784,12.496366);
var destinationG = new google.maps.LatLng(50.85034,4.35171);
var destinationH = new google.maps.LatLng(46.198392,6.142296);
var destinationI = new google.maps.LatLng(47.36865,8.539183);
var destinationJ = new google.maps.LatLng(53.408371,-2.991573);
var destinationK = new google.maps.LatLng(37.389092,-5.984459);
var destinationL = new google.maps.LatLng(53.349805,-6.26031);
var destinationM = new google.maps.LatLng(55.864237,-4.251806);
var destinationN = new google.maps.LatLng(51.92442,4.477733);
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destinationA, destinationB,destinationC, destinationD,destinationE, destinationF,destinationG, destinationH,destinationI, destinationJ,destinationK, destinationL, destinationM, destinationN],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
The OVER_QUERY_ERROR is coming from the geocoder, not the DistanceMatrix call. Remove this line:
addMarker(destinations[j], true);
(you don't need the geocoder, you already have the coordinates for the markers)
working code snippet:
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin = new google.maps.LatLng(55.930, -3.118);
var origin2 = 'Greenwich, England';
var destinationA = new google.maps.LatLng(45.465422, 9.185924);
var destinationB = new google.maps.LatLng(41.385064, 2.173403);
var destinationC = new google.maps.LatLng(40.416775, -3.70379);
var destinationD = new google.maps.LatLng(51.507351, -0.127758);
var destinationE = new google.maps.LatLng(48.856614, 2.352222);
var destinationF = new google.maps.LatLng(41.902784, 12.496366);
var destinationG = new google.maps.LatLng(50.85034, 4.35171);
var destinationH = new google.maps.LatLng(46.198392, 6.142296);
var destinationI = new google.maps.LatLng(47.36865, 8.539183);
var destinationJ = new google.maps.LatLng(53.408371, -2.991573);
var destinationK = new google.maps.LatLng(37.389092, -5.984459);
var destinationL = new google.maps.LatLng(53.349805, -6.26031);
var destinationM = new google.maps.LatLng(55.864237, -4.251806);
var destinationN = new google.maps.LatLng(51.92442, 4.477733);
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10
};
map = new google.maps.Map(document.getElementById('map-canvas'), opts);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
deleteOverlays();
var destinations = [destinationA, destinationB, destinationC, destinationD, destinationE, destinationF, destinationG, destinationH, destinationI, destinationJ, destinationK, destinationL, destinationM, destinationN];
for (var i = 0; i < destinations.length; i++) {
bounds.extend(destinations[i]);
var marker = new google.maps.Marker({
map: map,
position: destinations[i],
icon: destinationIcon
});
markersArray.push(marker);
}
map.fitBounds(bounds);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: destinations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
// addMarker(destinations[j], true);
outputDiv.innerHTML += "<b>"+j+":</b>"+origins[i] + ' to ' + destinations[j] + ': ' + results[j].distance.text + ' in ' + results[j].duration.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({
'address': location
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function deleteOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
width: 50%;
}
#content-pane {
float: right;
width: 48%;
padding-left: 2%;
}
#outputDiv {
font-size: 11px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<p>
<button type="button" onclick="calculateDistances();">Calculate distances</button>
</p>
</div>
<div id="outputDiv"></div>
</div>
<div id="map-canvas"></div>
I have a specific requirement where i have to display only railway stations in the map rather than the whole map. How can this be achieved.?. Please find the below code that i have tried.
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?libraries=drawing&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
// init map
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var drawingManager = new google.maps.drawing.DrawingManager();
drawingManager.setMap(map);
// init directions service
var dirService = new google.maps.DirectionsService();
var dirRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});
dirRenderer.setMap(map);
// highlight a street
// highlight a street
var request = {
origin: '',
destination: '',
travelMode: google.maps.TravelMode.TRANSIT
};
dirService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
dirRenderer.setDirections(response);
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var transitMode = steps[j].travel_mode;
if (transitMode == "TRANSIT") {
var vehicle = steps[j].transit.line.vehicle.type;
if (vehicle == "HEAVY_RAIL") {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
// polyline.getPath().push(nextSegment[k]);
}
}
}
}
}
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Any help will be much appreciated.. Thanks in advance..
I didn't understand what actually you want to do, but for this special kind of mapping you can rely on transit.js
It may be difficult,because:
Which is "Railway STATION"?, Platform?,Mark-on-rail?,Wickets?,Master'sRoom?,EntranceGate?
GoogleTransitService may show transfer by WALK via stair steps.