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);
Related
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 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.
How to combine the DirectionsService and PlacesService in google map. I will inspire on this path http://www.indiaproperty.com/godrej-palm-grove-in-poonamallee-chennai-pl4110632?fr=sres2 . I can't get the duration & distance of each location. I need to find each location distance and duration. I given the code below:
var map;
var infowindow;
var markersArray = [];
var pyrmont = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var places = [];
// var waypoints = [];
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 14,
zoomControl: false,
scaleControl: false,
scrollwheel: false,
disableDoubleClickZoom: true,
});
infowindow = new google.maps.InfoWindow();
//document.getElementById('directionsPanel').innerHTML='';
search_types();
}
function createMarker(place,icon) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
visible:true
});
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<b>Name:</b>"+place.name+"<br><b>Address:</b>"+place.vicinity+"<br><b>Reference:</b>"+place.reference+"<br><b>Rating:</b>"+place.rating+"<br><b>Id:</b>"+place.id);
infowindow.open(map, this);
});
}
var source="";
var dest='';
function search_types(latLng){
clearOverlays();
if(!latLng){
var latLng = pyrmont;
}
var placename = $('.nearby h3').attr("data-value")
var type = $('#valueStored').val();
var icon = "images/"+type+".png";
var request = {
location: latLng,
radius: 2000,
types: [type], //e.g. school, restaurant,bank,bar,city_hall,gym,night_club,park,zoo
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
$('.map-list').find('li').remove();
var service = new google.maps.places.PlacesService(map);
service.search(request, function(results, status) {
map.setZoom(14);
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
results[i].html_attributions='';
places[i] = results[i];
createMarker(results[i],icon);
$('.map-list').append('<li>'+results[i].name+'<div><span class="distance"></span> <span class="duration"></span></div></li>');
}
}
});
distanceCalc();
}
var latadd, longadd;
function distanceCalc(latLng){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var changeaddress;
var pyrmont1 = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var request = {
origin: pyrmont,
destination: pyrmont1,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var listed = $('.map-list li');
console.log(places[4]);
for (var i = 0; i < listed.length; i++) {
$('.distance').text(response.routes[0].legs[0].distance.value);
$('.duration').text(response.routes[0].legs[0].duration.value);
}
// Display the distance:
directionsDisplay.setDirections(response);
}
});
}
function showResult(result) {
latadd = result.geometry.location.lat();
longadd = result.geometry.location.lng();
}
// Deletes all markers in the array by removing references to them
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(false)
}
//markersArray.length = 0;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function clearMarkers(){
$('#show_btn').show();
$('#hide_btn').hide();
clearOverlays()
}
function showMarkers(){
$('#show_btn').hide();
$('#hide_btn').show();
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(true)
}
}
}
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 using google map to find route between two location.i want to get center latitude and longitude of the route. can u please tell me how to get center of the route.i am using the below code for getting routes,Thanks in advance
var map;
var directionsDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var infoWindow;
var service;
var lat1 = 0;
var lng1;
function pre_initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
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);
}
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var addressfrom = document.getElementById("from").value;
var addressto = document.getElementById("to").value;
var geocoder = new google.maps.Geocoder();
var coords = new google.maps.LatLng(0, 0);
alert(lat1);
coords = geocoder.geocode({ 'address': addressfrom }, function (results, status) {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
});
directionsService = new google.maps.DirectionsService();
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
// Instantiate an info window to hold step text.
infoWindow = new google.maps.InfoWindow();
stepDisplay = new google.maps.InfoWindow();
calcRoute();
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
radius: 100,
types: ['hospital', 'cafe', 'restaurant', 'food', 'bar'],
keyword: 'best view'
};
service = new google.maps.places.PlacesService(map);
//service.nearbySearch(request, callback);
service.radarSearch(request, callback);
//service.textSearch(request, callback);
}
function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon:
{
// Star
path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
fillColor: '#ff0000',
fillOpacity: 1,
scale: 1 / 4,
strokeColor: '#bd8d2c',
strokeWeight: 1
}
});
google.maps.event.addListener(marker, 'click', function () {
service.getDetails(place, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
});
});
}
function calcRoute() {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Now, clear the array itself.
markerArray = [];
var start = document.getElementById('from').value;
var end = document.getElementById('to').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response);
}
});
}
function showSteps(directionResult) {
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_point,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function () {
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
</script>
Refer to the code below:
self.adjustPosition = function () {
var lat = 0, lng = 0;
if (self.nearbyPlaces().length == 0) {
return false;
}
for (var i = 0; i < self.nearbyPlaces().length; i++) {
lat += self.nearbyPlaces()[i].latitude;
lng += self.nearbyPlaces()[i].longitude;
}
lat = lat / self.nearbyPlaces().length;
lng = lng / self.nearbyPlaces().length;
self.map.setCenter(new window.google.maps.LatLng(lat, lng));
};