i have try to calculate distance from 2 very far locations
and I expect that google give me a ZERO RESULT error becouse not find a right way from this 2 locations, but not give me this error And i can't intercept this error
just say me:
Uncaught TypeError: Cannot read property 'text' of undefined
Now my question is, how can i intercept this error ZERO RESULT?
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: -15.7942357,
lng: -47.8821945
}
});
var bounds = new google.maps.LatLngBounds;
var origin1 = {lat: -33.8688197, lng: 151.209295500000058};
var destinationB = {lat: 50.087, lng: 14.421};
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationB],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(asDestination) {
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode({'address': originList[i]},
showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
geocoder.geocode({'address': destinationList[j]},
showGeocodedAddressOnMap(true));
alert(results[j].distance.text);
alert(results[j].duration.text);
}
}
}
});
}
#map{
width:100%;
height:300px;
}
<html>
<head>
</head>
<body>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSpQw&libraries=places&callback=initMap">
</script>
</body>
</html>
As I've mentioned about, the request is okay, hence why it returns the status, okay, you need to check each element for its status. View the code below especially the line results[j].status !== "OK"
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: -15.7942357,
lng: -47.8821945
}
});
var bounds = new google.maps.LatLngBounds;
var origin1 = {
lat: -33.8688197,
lng: 151.209295500000058
};
var destinationB = {
lat: 50.087,
lng: 14.421
};
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationB],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(asDestination) {
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode({
'address': originList[i]
},
showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
geocoder.geocode({
'address': destinationList[j]
},
showGeocodedAddressOnMap(true));
if (results[j].status !== "OK") {
alert("Not okay");
return;
}
alert(results[j].distance.text);
alert(results[j].duration.text);
}
}
}
});
}
#map {
width: 100%;
height: 300px;
}
<html>
<head>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCp5RzbQjgID4oHJYe6VRGhKGXpQTGtCmw&libraries=places&callback=initMap">
</script>
</body>
</html>
Before alert do a check something like below
// check if it has results
if(results[j].status === "OK") {
// do something with result
alert(results[j].distance.text);
alert(results[j].duration.text);
}
Google Maps API Status Code.
Related
Im trying to find the distance matrix between two points in Google Maps API and im getting this error.
Uncaught TypeError: Cannot read property 'apply' of undefined
at distance_matrix.js:4
at Ku.j (distance_matrix.js:3)
at Object.c [as _jr083s] (common.js:110)
at DistanceMatrixService.GetDistanceMatrix?1m1&2s35.853308276088036&1m1&2s-
Im trying to get the distance matrix response so I can get the distance in miles. Heres the code that I have
function initMap() {
const momilets = { lat: 35.853308276088036, lng: -78.57256943168214};
const map = new google.maps.Map(document.getElementById('map'), {zoom: 12, center: momilets, disableDefaultUI: true});
const marker = new google.maps.Marker({position: momilets, map: map});
const geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', () => {
geocodeAddress(geocoder, map);
})
}
function geocodeAddress(geocoder, resultsMap) {
const address = document.getElementById('address').value;
geocoder.geocode({ address: address }, (results, status) => {
if(status = 'OK') {
resultsMap.setCenter(results[0].geometry.location);
const marker2 = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
});
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: ['35.853308276088036', '-78.57256943168214'],
destinations: [toString(lat), toString(lng)],
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: 'DRIVING'
} );
} else {
alert("Unsuccessful because: " + status);
}
});
}
function callback(response, status) {
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}
if anyone can help clear this error for me itd be greatly appreciated
you haven't provided callback function in service.getDistanceMatrix() method that's why getting the above error.
service.getDistanceMatrix({
origins: ['35.853308276088036', '-78.57256943168214'],
destinations: [toString(lat), toString(lng)],
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: 'DRIVING'
}, (response, status) => {
console.log("response data: ", response);
console.log("status: ", status);
});
You can follow the below JSFiddle link for complete working code.
<script async src="//jsfiddle.net/y4zbkudo/4/embed/js,html,css,result/dark/"></script>
I was following along with a tutorial involving the GoogleMaps API JS, and everything went well. When trying to building my own app I've come across an issue with displaying a route. The application I'm working on is mainly written in ruby on rails.
The "pseudo code" problem is when clicking on to "view route" button, the route is not displaying on the map.
Below is the HTML that triggers the first event when clicking on the search with in time button, and the CSS as requested.
<body>
<div>
<span class="text"> Within </span>
<select id='max-duration'>
<option value="10">10 min</option>
</select>
<select id="mode">
<option value="DRIVING">drive</option>
</select>
<span class="text">of</span>
<input id= 'search-within-time-text' type='text' placeholder='Your Location'>
<input id= 'search-within-time' type='button' value='Go'>
</div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places,drawing,geometry&key=<%= ENV["MAP_API"] %>&v=3"></script>
</body>
<style>
#map {
bottom: 0px;
height: 500px;
left: 362px;
position: absolute;
right: 0px;
}
.container {
height: 500px;
position: relative;
}
.options-box {
background: #fff;
border: 1px solid black;
height: 91.75%;
line-height: 35px;
padding: 10px 10px 30px 10px;
text-align: left;
width: 340px;
}
#zoom-to-area-text{
width:200px;
}
</style>
The location array that is stroing the data is found in the maps controller, where we are pushing data from our SQLite DB.
def index
#test_array = []
#test.each do |h|
#test_array.push({lat: h.lat, lng: h.lng})
end
end
In particular I believe the problem lays within the function displayDirections. Which can be found at the bottom of the full code
The displayDirections function is written outside of the initMap function, because of a scoping issue when it is written inside of the initMap function. I've read the problem below
Maybe a similar issue
But had issues with displayDirections being defined at the click event, when it was written with in the initMap function, in the function displayMarkersWithinTime.
Any help is appreciated! Thanks!
function initMap() {
var map;
var markers = [];
var placeMarkers = [];
document.getElementById('search-within-time').addEventListener('click', function(){
searchWithinTime();
});
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.9523789, lng: -75.1635996},
zoom: 13,
mapTypeControl: false
});
var locations = <%= raw #test_array.to_json%>
for (var i = 0; i < locations.length; i++) {
var position = locations[i]
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.DROP,
id: i
});
markers.push(marker);
}
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++){
markers[i].setMap(null);
}
}
function searchWithinTime(){
var distanceMatrixService = new google.maps.DistanceMatrixService;
var address = document.getElementById('search-within-time-text').value;
if (address == ''){
window.alert('You must enter an address.');
} else {
hideMarkers(markers);
var origins = [];
for (var i = 0; i < markers.length; i++) {
origins[i] = markers[i].position;
}
var destination = address;
var mode = document.getElementById('mode').value;
distanceMatrixService.getDistanceMatrix({
origins: origins,
destinations: [destination],
travelMode: google.maps.TravelMode[mode],
unitSystem: google.maps.UnitSystem.IMPERIAL,
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
window.alert('Error was: ' + status);
} else {
displayMarkersWithinTime(response);
}
});
}
}
function displayMarkersWithinTime(response){
var maxDuration = document.getElementById('max-duration').value;
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var atLeastOne = false;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
if (element.status === "OK") {
var distanceText = element.distance.text;
var duration = element.duration.value / 60;
var durationText = element.duration.text;
if (duration <= maxDuration) {
markers[i].setMap(map);
atLeastOne = true;
var infowindow = new google.maps.InfoWindow({
content : durationText + ' away, ' + distanceText + '<div><input type=\"button\" value=\"View Route\" onclick =' + '\"displayDirections("' + origins[i] + '");\"</input></div>'
});
infowindow.open(map, markers[i]);
// if user clicks on marker close the small info window to open a new
markers[i].infowindow = infowindow;
google.maps.event.addListener(markers[i], 'click', function (){
this.infowindow.close();
});
}
}
}
}
if(!atLeastOne) {
window.alert('We could not find any locations within that distance');
}
console.log("hello")
}
}
var map;
var markers = [];
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.9523789, lng: -75.1635996},
zoom: 13,
mapTypeControl: false
});
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++){
markers[i].setMap(null);
}
}
function displayDirections(origin) {
hideMarkers(markers);
var directionsService = new google.maps.DirectionsService;
var destinationAddress = document.getElementById('search-within-time-text').value;
var mode = document.getElementById('mode').value;
directionsService.route({
origin: origin,
destination: destinationAddress,
travelMode: google.maps.TravelMode[mode]
}, function(response, status) {
console.log(response)
console.log(status)
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
draggable: true,
polylineOptions: {
strokeColor: 'black'
}
}, console.log(map), console.log(response));
} else {
window.alert('Directions request failed due to ' + status);
}
});
console.log("testing")
}
google.maps.event.addDomListener(window, initMap())
Your (initialized) map variable is local to the initMap function. Make it global.
Change:
function initMap() {
var map;
// ...
To:
var map;
function initMap() {
proof of concept fiddle
code snippet:
var map;
function initMap() {
var markers = [];
var placeMarkers = [];
var titles;
var latitudes;
var longitudes;
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
document.getElementById('show-listings').addEventListener('click', showListings);
document.getElementById('hide-listings').addEventListener('click', function() {
hideMarkers(markers);
});
document.getElementById('search-within-time').addEventListener('click', function() {
searchWithinTime();
});
var timeAutocomplete = new google.maps.places.Autocomplete(
document.getElementById('search-within-time-text'));
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 39.9523789,
lng: -75.1635996
},
zoom: 13,
mapTypeControl: false
});
var locations = [{
lat: 39.952584,
lng: -75.165222
}, {
lat: 47.6062095,
lng: -122.3320708
},
{
lat: 34.0522342,
lng: -118.2436849
},
{
lat: 39.114053,
lng: -94.6274636
}, {
lat: 25.7616798,
lng: -80.1917902
}
];
for (var i = 0; i < locations.length; i++) {
var position = locations[i]
var marker = new google.maps.Marker({
position: position,
animation: google.maps.Animation.DROP,
id: i,
map: map
});
markers.push(marker);
}
function showListings() {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
bounds.extend(markers[i].position);
}
map.fitBounds(bounds);
}
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function searchWithinTime() {
var distanceMatrixService = new google.maps.DistanceMatrixService();
var address = document.getElementById('search-within-time-text').value;
if (address == '') {
window.alert('You must enter an address.');
} else {
hideMarkers(markers);
var origins = [];
for (var i = 0; i < markers.length; i++) {
origins[i] = markers[i].position;
}
var destination = address;
var mode = document.getElementById('mode').value;
distanceMatrixService.getDistanceMatrix({
origins: origins,
destinations: [destination],
travelMode: google.maps.TravelMode[mode],
unitSystem: google.maps.UnitSystem.IMPERIAL,
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
window.alert('Error was: ' + status);
} else {
displayMarkersWithinTime(response);
}
});
}
}
function displayMarkersWithinTime(response) {
var maxDuration = document.getElementById('max-duration').value;
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var atLeastOne = false;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
if (element.status === "OK") {
var distanceText = element.distance.text;
var duration = element.duration.value / 60;
var durationText = element.duration.text;
if (duration <= maxDuration) {
markers[i].setMap(map);
atLeastOne = true;
var infowindow = new google.maps.InfoWindow({
content: durationText + ' away, ' + distanceText + '<div><input type=\"button\" value=\"View Route\" onclick =' + '\"displayDirections("' + origins[i] + '");\"</input></div>'
});
infowindow.open(map, markers[i]);
// if user clicks on marker close the small info window to open a new
markers[i].infowindow = infowindow;
google.maps.event.addListener(markers[i], 'click', function() {
this.infowindow.close();
});
}
}
}
}
if (!atLeastOne) {
window.alert('We could not find any locations within that distance');
}
console.log("hello")
}
}
var map;
var markers = [];
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 39.9523789,
lng: -75.1635996
},
zoom: 13,
mapTypeControl: false
});
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
function displayDirections(origin) {
hideMarkers(markers);
var directionsService = new google.maps.DirectionsService();
var destinationAddress = document.getElementById('search-within-time-text').value;
var mode = document.getElementById('mode').value;
directionsService.route({
origin: origin,
destination: destinationAddress,
travelMode: google.maps.TravelMode[mode]
}, function(response, status) {
console.log(response)
console.log(status)
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
draggable: true,
polylineOptions: {
strokeColor: 'black'
}
}, console.log(map), console.log(response));
} else {
window.alert('Directions request failed due to ' + status);
}
});
console.log("testing")
}
google.maps.event.addDomListener(window, 'load', initMap)
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
background-color: white;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" value="search" id="search-within-time" />
<input type="text" value="coffee" id="search-within-time-text" />
<input type="button" value="Show" id="show-listings" />
<input type="button" value="Hide" id="hide-listings" />
<input type="text" value="DRIVING" id="mode" />
<input type="text" value="1200" id="max-duration" />
<div id="map"></div>
I Strucked while calculating RoadMap distance between 2 locations of lat longs using JavaScript.
Found answer :
with this link :
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1],
destinations: [destinationA],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
return;
}
https://jsfiddle.net/c6omLvso/
Are you using the google maps javascript api? if so u can try the "Distance Matrix Service"
You can achieve your goal using the google distance matrix like this:
google.maps.event.addDomListener(window, "load", function () {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var origin1 = {lat: 55.93, lng: -3.118};
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = {lat: 50.087, lng: 14.421};
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
return;
}
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var output = document.getElementById("output");
output.innerHTML = "";
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
output.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
});
});
body {
margin: 0;
padding: 0;
font: 12px sans-serif;
}
#map {
width: 400px;
height: 400px;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map"></div>
<div id="output"></div>
enter code here
i have variable array 2 dimentional:
var locations = new Array(3);
for (var i = 0; i < 3; i++) {
locations[i] = ['1', '2', '3'];
}
and i have array with name Place inside
data = ["Terogong, Indonesia", "Blok M, Indonesia", "Cipinang, Indonesia"]
when i use Geocoder to search Lat and Lang, then its fill Locations[] with name place, Lat and Lang:
for (var i = 0; i < data.length-1; i++) {
var c = data[i];
geocoder.geocode( { 'address': data[i] + ", indonesia"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
locations[i] = [c , results[0].geometry.location.lat(), results[0].geometry.location.lng()];
alert(locations[i]);
} else {
alert("Something got wrong " + status);
}
});
}
and then, when i alert(locations[0]) its apear 1.
why this is happen??
The geocoder is asynchronous. One option is to use function closure to associate the variables in the request with the callback function:
for (var i = 0; i < data.length; i++) {
geocoder.geocode({
'address': data[i] + ", indonesia"
}, (function(data, i) { return function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
locations[i] = [data, results[0].geometry.location.lat(), results[0].geometry.location.lng()];
var mark = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: data
});
// alert(locations[i]);
} else {
alert("Something got wrong " + status);
}
}}(data[i], i))); // has function closure on data[i] as data, i (as i)
}
working fiddle
code snippet:
var geocoder = new google.maps.Geocoder();
var map;
var data = ["Terogong, Indonesia", "Blok M, Indonesia", "Cipinang, Indonesia"];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var locations = new Array(3);
for (var i = 0; i < 3; i++) {
locations[i] = ['1', '2', '3'];
}
for (var i = 0; i < data.length; i++) {
geocoder.geocode({
'address': data[i] + ", indonesia"
}, (function(data, i) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
locations[i] = [data, results[0].geometry.location.lat(), results[0].geometry.location.lng()];
var mark = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: data
});
} else {
alert("Something got wrong " + status);
}
}
}(data[i], i)));
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
I am facing a problem with my Google Maps API. I had the script created from a developer who has dissappeared and will not reply to me haha
It was working a few weeks ago and all of a sudden has stopped working when I started to test the entire site. I can't find what is wrong with it. I need someone to please help me on this as I am new to Google Maps API.
The script should find places around the given address.
The way it should work is:
The script grabs an address from the page
Using Googles Geocode API converts the address to get lang/lat values
Then using Google Places API posts the lang/lat to get the places around the address.
I have debugged the script and it seems like the Geocode API is working and when we query Google Places API nothing is retrieved back.
I am using the latest JQuery library and the following Google API library: https://maps.googleapis.com/maps/api/js?libraries=places
Please find the code below:
$(document).ready(function()
{
address = $("#address").text();
});
var map;
var infowindow;
var map;
var map_street;
var service;
var service_local_info;
var request_school;
var request_restaurant;
var request_healthcare;
var request_foodstores;
var restaurant_markers = [];
var school_markers = [];
var healthcare_markers = [];
var foodstores_markers = [];
var latitude;
var longitude;
var panorama;
var panoramaOptions;
var schoolName;
var trafficLayer;
var address = "";
var infowindow;
var counter = 0;
function trafic()
{
if($("#trafic").is(":checked"))
{
trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
}
else
{
trafficLayer.setMap(null);
}
}
function street_view()
{
panorama = new google.maps.StreetViewPanorama(document.getElementById("street-view"), panoramaOptions);
map.setStreetView(panorama);
}
function local_info()
{
$("#distance_school").html('<div class="breadcrumb"><i class="glyphicon glyphicon-certificate"></i> Schools</div>');
$("#distance_restaurant").html('<div class="breadcrumb"><i class="glyphicon glyphicon-cutlery"></i> Restaurants</div>');
$("#distance_healthcare").html('<div class="breadcrumb"><i class="glyphicon glyphicon-heart"></i> Health Care</div>');
$("#distance_foodstores").html('<div class="breadcrumb"><i class="glyphicon glyphicon-glass"></i> Food Stores</div>');
var location_local_info;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
location_local_info = results[0].geometry.location;
latitude = location_local_info.k;
longitude = location_local_info.D;
map = new google.maps.Map(document.getElementById('map2'), {
center: location_local_info,
zoom: 15
});
service = new google.maps.places.PlacesService(map);
request_school = {
location: location_local_info,
radius: 500,
types: ["school"]
};
service.nearbySearch(request_school, school_local_info_callback);
request_restaurant = {
location: location_local_info,
radius: 500,
types: ["restaurant"]
};
service.nearbySearch(request_restaurant, restaurant_local_info_callback);
request_healthcare = {
location: new google.maps.LatLng(latitude, longitude),
radius: 500,
types: ["health"]
};
service.nearbySearch(request_healthcare, healthcare_local_info_callback);
request_foodstores = {
location: new google.maps.LatLng(latitude, longitude),
radius: 500,
types: ["food"]
};
service.nearbySearch(request_foodstores, foodstores_local_info_callback);
}
else
{
alert("error in location");
}
});
}
function healthcare()
{
if($("#healthcare").is(":checked"))
{
request_healthcare = {
location: new google.maps.LatLng(latitude, longitude),
radius: 500,
types: ["health"]
};
service.nearbySearch(request_healthcare, healthcare_marker);
}
else
{
for(i=0; i<healthcare_markers.length; i++)
{
healthcare_markers[i].setMap(null);
}
}
}
function foodstores()
{
if($("#foodstores").is(":checked"))
{
request_foodstores = {
location: new google.maps.LatLng(latitude, longitude),
radius: 500,
types: ["food"]
};
service.nearbySearch(request_foodstores, foodstores_marker);
}
else
{
for(i=0; i<foodstores_markers.length; i++)
{
if(foodstores_markers[i])
{
foodstores_markers[i].setMap(null);
}
}
}
}
function school()
{
if($("#school").is(":checked"))
{
request_school = {
location: new google.maps.LatLng(latitude, longitude),
radius: 500,
types: ["school"] //school,
};
service.nearbySearch(request_school, school_marker);
}
else
{
for(i=0; i<school_markers.length; i++)
{
school_markers[i].setMap(null);
}
}
}
function restaurant()
{
if($("#restaurant").is(":checked"))
{
request_restaurant =
{
location: new google.maps.LatLng(latitude, longitude),
radius: 500,
types: ["restaurant"] //school,
};
service.nearbySearch(request_restaurant, restaurant_marker);
}
else
{
for(i=0; i<restaurant_markers.length; i++)
{
restaurant_markers[i].setMap(null);
}
}
}
function initialize()
{
$('#restaurant').attr('checked', false);
$('#school').attr('checked', false);
$('#trafic').attr('checked', false);
$('#healthcare').attr('checked', false);
$('#foodstores').attr('checked', false);
var location;;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
location = results[0].geometry.location;
latitude = location.k;
longitude = location.D;
map = new google.maps.Map(document.getElementById('map2'), {
center: location,
zoom: 15
});
map_street = new google.maps.Map(document.getElementById('street-view'), {
center: location,
zoom: 15
});
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.BOUNCE,
//icon:"restaurant.jpg",
position: location
});
service = new google.maps.places.PlacesService(map);
panoramaOptions = {
position: location,
pov: {
heading: 34,
pitch: 10
}
};
}
else
{
alert("error in location");
}
});
}
function restaurant_marker(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length; i++)
{
restaurant_markers[i] = new google.maps.Marker({
map: map,
//icon:"restaurant.jpg",
position: results[i].geometry.location
});
google.maps.event.addListener(restaurant_markers[i], 'click', function()
{
if(infowindow)
{
infowindow.close();
}
for(var j=0; j<results.length; j++)
{
if(results[j].geometry.location.k == this.position.k && results[j].geometry.location.D == this.position.D )
{
infowindow = new google.maps.InfoWindow({
content: "<div style='overflow-y:none;'><b>Name</b> : "+results[j].name+"<br><b>Address</b> : "+results[j].vicinity+"</div>",
maxWidth: 1000,
maxHeight: 3000
});
infowindow.open(map,this);
}
}
});
}
}
}
function school_marker(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length; i++)
{
school_markers[i] = new google.maps.Marker({
map: map,
//icon:"school.png",
position: results[i].geometry.location
});
google.maps.event.addListener(school_markers[i], 'click', function()
{
if(infowindow)
{
infowindow.close();
}
for(var j=0; j<results.length; j++)
{
if(results[j].geometry.location.k == this.position.k && results[j].geometry.location.D == this.position.D )
{
infowindow = new google.maps.InfoWindow({
content: "<div style='overflow-y:none;'><b>Name</b> : "+results[j].name+"<br><b>Address</b> : "+results[j].vicinity+"</div>",
maxWidth: 1000,
maxHeight: 3000
});
infowindow.open(map,this);
}
}
});
}
}
}
function healthcare_marker(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length; i++)
{
healthcare_markers[i] = new google.maps.Marker({
map: map,
//icon:"school.png",
position: results[i].geometry.location
});
google.maps.event.addListener(healthcare_markers[i], 'click', function()
{
if(infowindow)
{
infowindow.close();
}
for(var j=0; j<results.length; j++)
{
if(results[j].geometry.location.k == this.position.k && results[j].geometry.location.D == this.position.D )
{
infowindow = new google.maps.InfoWindow({
content: "<div style='overflow-y:none;'><b>Name</b> : "+results[j].name+"<br><b>Address</b> : "+results[j].vicinity+"</div>",
maxWidth: 1000,
maxHeight: 3000
});
infowindow.open(map,this);
}
}
});
}
}
}
function foodstores_marker(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length; i++)
{
if(results[i].types.indexOf("restaurant") == -1)
{
foodstores_markers[i] = new google.maps.Marker({
map: map,
//icon:"school.png",
position: results[i].geometry.location
});
google.maps.event.addListener(foodstores_markers[i], 'click', function()
{
if(infowindow)
{
infowindow.close();
}
for(var j=0; j<results.length; j++)
{
if(results[j].types.indexOf("restaurant") == -1)
{
if(results[j].geometry.location.k == this.position.k && results[j].geometry.location.D == this.position.D )
{
infowindow = new google.maps.InfoWindow({
content: "<div style='overflow-y:none;'><b>Name</b> : "+results[j].name+"<br><b>Address</b> : "+results[j].vicinity+"</div>",
maxWidth: 1000,
maxHeight: 3000
});
infowindow.open(map,this);
}
}
}
});
}
}
}
}
function school_local_info_callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length && i < 6; i++)
{
calculate_distance_school(results[i].geometry.location, results[i].name);
}
}
}
function restaurant_local_info_callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length && i < 6; i++)
{
calculate_distance_restaurant(results[i].geometry.location, results[i].name);
}
}
}
function healthcare_local_info_callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length && i < 6; i++)
{
calculate_distance_healthcare(results[i].geometry.location, results[i].name);
}
}
}
function foodstores_local_info_callback(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for (var i = 0; i < results.length; i++)
{
if(results[i].types.indexOf("restaurant") == -1)
{
calculate_distance_foodstores(results[i].geometry.location, results[i].name);
counter++;
if(counter == 6)
break;
}
}
counter = 0;
}
}
function calculate_distance_school(origin, name)
{
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [new google.maps.LatLng(latitude, longitude)],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function (response, status)
{
if (status == google.maps.DistanceMatrixStatus.OK)
{
var result = response.rows[0].elements;
$("#distance_school").append("<div class=\"col-xs-12 col-sm-4 col-md-4 local-body\"><h4>"+name+"</h4><p><strong>Distance :</strong> "+result[0].distance.text+"les</p></div>");
}
else
{
alert(status);
}
});
}
function calculate_distance_restaurant(origin, name)
{
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [new google.maps.LatLng(latitude, longitude)],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function (response, status)
{
if (status == google.maps.DistanceMatrixStatus.OK)
{
var result = response.rows[0].elements;
$("#distance_restaurant").append("<div class=\"col-xs-12 col-sm-4 col-md-4 local-body\"><h4>"+name+"</h4><p><strong>Distance :</strong> "+result[0].distance.text+"les</p></div>");
}
else
{
alert(status);
}
});
}
function calculate_distance_healthcare(origin, name)
{
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [new google.maps.LatLng(latitude, longitude)],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function (response, status)
{
if (status == google.maps.DistanceMatrixStatus.OK)
{
var result = response.rows[0].elements;
$("#distance_healthcare").append("<div class=\"col-xs-12 col-sm-4 col-md-4 local-body\"><h4>"+name+"</h4><p><strong>Distance :</strong> "+result[0].distance.text+"les</p></div>");
}
else
{
alert(status);
}
});
}
function calculate_distance_foodstores(origin, name)
{
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [new google.maps.LatLng(latitude, longitude)],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function (response, status)
{
if (status == google.maps.DistanceMatrixStatus.OK)
{
var result = response.rows[0].elements;
$("#distance_foodstores").append("<div class=\"col-xs-12 col-sm-4 col-md-4 local-body\"><h4>"+name+"</h4><p><strong>Distance :</strong> "+result[0].distance.text+"les</p></div>");
}
else
{
alert(status);
}
});
}
I didn't verify but you should try to use one service per request:
service = new google.maps.places.PlacesService(map);
...
service.nearbySearch(request_school, school_local_info_callback);
service2 = new google.maps.places.PlacesService(map);
...
service2.nearbySearch(request_restaurant, restaurant_local_info_callback);