Currently I have encounter a problem. I used and changed sample API to draw route for two points. Point A is current location. Point B is one of the multiple markers' location. Those markers are created which I call nearby search function.
function showInfoWindow() {
var marker = this;
places.getDetails({
placeId: marker.placeResult.place_id
},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
var clickLat = marker.position.lat();
var clickLon = marker.position.lng();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var directionsService = new google.maps.DirectionsService();
showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}
function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
var pointA = {
lat: currentLat,
lng: currentLon
};
var pointB = {
lat: clickLat,
lng: clickLon
};
directionsDisplay.setOptions({
suppressMarkers: true
});
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
// Set destination, origin and travel mode.
var request = {
destination: pointB,
origin: pointA,
travelMode: google.maps.TravelMode.DRIVING
};
//directionsDisplay.setMap(null);
// Pass the directions request to the directions service.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
//directionsDisplay.set('directions', null);
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
These codes could draw route for two points already. But the problem is when I click one marker call the showInfoWindow() it will draw one route, and click another one when it will call the showInfoWindow() again it will draw another route remaining the previous one route.I want to clear the previous one route. Tried all the methods online and could not find the reason.
If you only want one directions result displayed on the map at the time, only create and use one instance of the DirectionsRenderer, currently you create a new one for every result from the DirectionsService.
proof of concept fiddle
code snippet:
var geocoder;
var map;
var places;
var infoWindow = new google.maps.InfoWindow();
//Jersey City, NJ, USA
var currentLat = 40.7281575;
var currentLon = -74.0776417;
// global reference to the DirectionsRenderer
var directionsDisplay;
function initialize() {
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
});
places = new google.maps.places.PlacesService(map);
// initialize the global DirectionsRenderer
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var marker1 = new google.maps.Marker({ /* New York, NY, USA */
position: {
lat: 40.7127837,
lng: -74.0059413
},
placeResult: {
place_id: "ChIJOwg_06VPwokRYv534QaPC8g"
},
map: map
});
google.maps.event.addListener(marker1, 'click', showInfoWindow);
var marker2 = new google.maps.Marker({ /* Newark, NJ, USA */
position: {
lat: 40.735657,
lng: -74.1723667
},
placeResult: {
place_id: "ChIJHQ6aMnBTwokRc-T-3CrcvOE"
},
map: map
});
google.maps.event.addListener(marker2, 'click', showInfoWindow);
var bounds = new google.maps.LatLngBounds();
bounds.extend(marker1.getPosition());
bounds.extend(marker2.getPosition());
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
function showInfoWindow() {
var marker = this;
places.getDetails({
placeId: marker.placeResult.place_id
},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
var clickLat = marker.position.lat();
var clickLon = marker.position.lng();
var directionsService = new google.maps.DirectionsService();
showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}
function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
var pointA = {
lat: currentLat,
lng: currentLon
};
var pointB = {
lat: clickLat,
lng: clickLon
};
directionsDisplay.setOptions({
suppressMarkers: true
});
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
// Set destination, origin and travel mode.
var request = {
destination: pointB,
origin: pointA,
travelMode: google.maps.TravelMode.DRIVING
};
//directionsDisplay.setMap(null);
// Pass the directions request to the directions service.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
//directionsDisplay.set('directions', null);
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
Related
I want to check if there is a marker on my route.. So i tried to use isLocationOnEdge() and i am getting "TypeError:b.get is not a function" error.
Here is my code i tried several changes but couldn't fix the problem.
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: my_position.getPosition(),
destination: new google.maps.LatLng(my_markers[0][0],my_markers[0][1]),
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
var isLocationOnEdge = google.maps.geometry.poly.isLocationOnEdge;
var path = response.routes[0].overview_path;
for (var i = 0; i < my_markers.length; i++) {
if (isLocationOnEdge(new google.maps.LatLng(my_markers[i][0],my_markers[i][1]),path))
{
console.log("Its in!")
}
}
});
According to the documentation, teh isLocationOnEdge method takes the following arguments:
isLocationOnEdge(point:LatLng, poly:Polygon|Polyline, tolerance?:number)
Return Value: boolean
Computes whether the given point lies on or near to a polyline, or the edge of a polygon, within a specified tolerance. Returns true when the difference between the latitude and longitude of the supplied point, and the closest point on the edge, is less than the tolerance. The tolerance defaults to 10-9 degrees.
The overview_path is not a google.maps.Polyline (or a Polygon), it is an array of google.maps.LatLng objects.
If I use that path to create a polyline, it works for me
var isLocationOnEdge = google.maps.geometry.poly.isLocationOnEdge;
var path = response.routes[0].overview_path;
var polyline = new google.maps.Polyline({
path: path
})
if (isLocationOnEdge(new google.maps.LatLng(37.438442, -122.157558), polyline, 1e-3)) {
console.log("Its in!")
}
proof of concept fiddle
code snippet:
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,
styles: [{
featureType: 'poi',
stylers: [{
visibility: 'off'
}]
}]
});
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: "Palo Alto, CA",
destination: "Stanford, CA",
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
var isLocationOnEdge = google.maps.geometry.poly.isLocationOnEdge;
var path = response.routes[0].overview_path;
var polyline = new google.maps.Polyline({
path: path
})
if (isLocationOnEdge(new google.maps.LatLng(37.438442, -122.157558), polyline, 1e-3)) {
console.log("Its in!")
var mark = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(37.438442, -122.157558),
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
},
title: "On Route"
});
var infowindow = new google.maps.InfoWindow({
content: "on route"
});
infowindow.open(map, mark);
}
});
}
}
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?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
I have an application which displays postcodes from a database, when a button is clicked the postcodes are geocoded and displayed as markers on a Google map in a pop up window. I'm trying to show the driving route between the two markers on the map. I have saved the geocoded values into HTML span tags and I'm trying to use these values as the origin and destination for the route. Everything works apart from the route showing between the markers which shows an error message 'Directions request failed due to NOT_FOUND'.
Any idea how I can get the route to show up?
$(document).ready(function () {
$(".openMap").click(function () {
var directionsService = new google.maps.DirectionsService;
var mapLocation = $(this).prev().prev().prev().text();
var secondMarker = $(this).prev().prev().text();
window.markers = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: mapLocation }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
directionsDisplay.setMap(map);
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Departure Location" });
markers.push(marker);
$('#route1').text(results[0].geometry.location);
}
});
var geocoder2 = new google.maps.Geocoder();
geocoder.geocode({ address: secondMarker }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Destination Location" });
markers.push(marker2);
$('#route2').text(results[0].geometry.location);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
});
directionsService.route({
origin: $('#route1').text(),
destination: $('#route2').text(),
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
$("#map").dialog({ title: "Lift Location ", height: 500, width: 500, modal: true });
});
});
route1 and route2 are empty. The API doesn't know how to create a route from "" to "".
Once I fix that (to use post1 and post2 which contain the postcodes), I get a javascript error: Uncaught ReferenceError: directionsDisplay is not defined.
Fixing that shows me a route.
proof of concept fiddle
code snippet:
$(document).ready(function() {
var directionsDisplay;
$(".openMap").click(function() {
var directionsService = new google.maps.DirectionsService;
var mapLocation = $(this).prev().prev().prev().text();
var secondMarker = $(this).prev().prev().text();
window.markers = [];
var geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
geocoder.geocode({
address: mapLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionsDisplay.setMap(map);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "Departure Location"
});
markers.push(marker);
$('#route1').text(results[0].geometry.location);
}
});
var geocoder2 = new google.maps.Geocoder();
geocoder.geocode({
address: secondMarker
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "Destination Location"
});
markers.push(marker2);
$('#route2').text(results[0].geometry.location);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
});
console.log("post1:" + $('.post1').text());
console.log("post2:" + $('.post2').text());
directionsService.route({
origin: $('.post1').text(),
destination: $('.post2').text(),
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
if (!directionsDisplay || !directionsDisplay.getMap || (directionsDisplay.getMap() == null)) {
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionsDisplay.setMap(map);
}
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
$("#map").dialog({
title: "Lift Location ",
height: 500,
width: 500,
modal: true
});
$(".selector").dialog({
resizeStop: function(event, ui) {
google.maps.event.trigger(map, 'resize');
}
});
$(".selector").dialog({
open: function(event, ui) {
google.maps.event.trigger(map, 'resize');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maps.google.com/maps/api/js"></script>
<div id="map" style="display: none;">
</div>
<span class='post1'>G1 3SL</span>
<span class='post2'>G1 2AF</span>
<br/>
<button class='openMap'>View On Map</button>
<br/>
<span id="route1"></span>
<span id="route2"></span>
I have this Javascript code on Google maps with geolocation and direction and I am using it in cordova , it gives me problems because it lacks the event Deviceready.
I tried to put it , but it was not working.
You are able to add it in the right way ?
Code:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
// default location. When geolocation tracks the client, this variable is set to that location
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//here there is marker
directionsDisplay.setMap(map);
map.setCenter(mylocation);
}
function updateRoute() {
calcRoute(mylocation);
}
function calcRoute(start) {
var start = mylocation;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.WALKING,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
mylocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//document.getElementById('start').value = ;
if (map) {
calcRoute(position.coords.latitude +','+ position.coords.longitude);
map.setCenter(mylocation);
//*Posizione Utente*//
var image = 'user.png'
var marker1 = new google.maps.Marker({
position: mylocation,
map: map,
title: 'ciao!',
icon: image
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.open(map,marker1);
});
var infowindow1 = new google.maps.InfoWindow({
content: '<img src="user.png">Sono Qui.....'
});
}
})
}
google.maps.event.addDomListener(window, 'load', initialize);
I'm working on a site that uses google maps v3, thanks to which you can navigate to a specific location
web site - http://dev.fama.net.pl/walendia/lokalizacja.html
type 'szczecin' on input that is at the top of the site and click submit - a marker will appear on the map, then type 'warszawa' - new marker will appear on the map but old one is still there, how to remove previous marker from the map
GOOGLE MAP CODE
var map;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();
var stepDisplay;
var markersArray = [];
var iconSize = new google.maps.Size(158,59);
var iconOrigin = new google.maps.Point(0,0);
var iconAnchor = new google.maps.Point(20,59);
function initialize(center, zoom) {
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
var mapOptions = {
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_RIGHT
}
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
geocoder.geocode({address: center}, function(results, status) {
map.setCenter(results[0].geometry.location);
});
}
function addMarker(location, icon) {
geocoder.geocode({address: location}, function(results, status) {
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon: icon
});
google.maps.event.addListener(marker);
markersArray.push(marker);
});
}
function addMarker2(position, icon) {
var location = new google.maps.LatLng(52.08901624831595, 20.854395031929016);
var icon = {
url: 'http://dev.fama.net.pl/walendia/img/markers/end.png',
size: iconSize,
origin: iconOrigin,
anchor: iconAnchor
}
marker = new google.maps.Marker({
position: location,
map: map,
icon: icon
});
markersArray.push(marker);
}
function calcRoute(start, end) {
var start = start;
var end = end;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var location = start;
var icon = {
url: 'http://dev.fama.net.pl/walendia/img/markers/start.png',
size: iconSize,
origin: iconOrigin,
anchor: iconAnchor
}
addMarker(location, icon);
addMarker2(location, icon);
directionsDisplay.setDirections(result);
}
});
}
// SET CENTER ON RESIZE
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
directionsDisplay.setMap(map);
});
$(document).ready(function() {
$('.form-box form').submit(function() {
var start = $(this).find('input[name="start"]').val();
var end = new google.maps.LatLng(52.08901624831595, 20.854395031929016);
directionsDisplay.setMap(map);
calcRoute(start, end);
return false;
});
});
HTML CODE
$(document).ready(function() {
initialize('Łączności 131, 05-552 Łazy, Polska', 10);
addMarker2(location);
});
Before adding second marker you need to delete marker from markersArray. Use the following function to delete markers from array.
function deleteMarkers() {
if (markersArray) {
for (i=0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
DEMO FIDDLE
NOTE: I just took some sample to remove and show markers when you click on buttons. Use those functions according to your requirement.
Kindly check this map view: http://gmaps-samples-v3.googlecode.com/svn/trunk/map_language/map_lang.html
If you click on A or B, it will show location name in default marker. I wish to show some custom texts here. How can I do that?
My JavaScript code for this is:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var oldDirections = [];
var currentDirections = null;
//getting latitude and longitude from address
var latitude;
var longitude;
var geocoder = new google.maps.Geocoder();
var address = "Downtown Berkeley";
geocoder.geocode( { "address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
// do something with the geocoded result
//
latitude = results[0].geometry.location.lat()
longitude = results[0].geometry.location.lng()
alert(latitude )
}
});
//map initialize
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(-33.879,151.235),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//adding marker
var marker = new google.maps.Marker
(
{
position: new google.maps.LatLng(latitude , longitude),
map: map,
title: "Click me"
}
);
var infowindow = new google.maps.InfoWindow({
content: "Location info:<br/>Country Name:<br/>LatLng:"
});
google.maps.event.addListener(marker, "click", function () {
// Calling the open method of the infoWindow
infowindow.open(map, marker);
});
directionsDisplay = new google.maps.DirectionsRenderer({
"map": map,
"preserveViewport": true,
"draggable": true
});
directionsDisplay.setPanel(document.getElementById("directions_panel"));
google.maps.event.addListener(directionsDisplay, "directions_changed",
function() {
if (currentDirections) {
oldDirections.push(currentDirections);
}
currentDirections = directionsDisplay.getDirections();
});
calcRoute();
}
function calcRoute() {
var start = "El Cerrito del Norte";
var end = "Downtown Berkeley";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
You set that content in the createInfoWindow() method.