Direction API google - direction request failed due to not found - javascript

I am trying to show the distance between two points. but i am facing this error direction request failed due to not found. I googled but not found a solution. Please have a look at my code and tell me if i am doing something wrong.
function initAutocomplete() {
var markerArray = [];
// Instantiate a directions service.
var directionsService = new google.maps.DirectionsService;
// Create a map and center it on Manhattan.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
center: {lat: 40.771, lng: -73.974}
});
// Create a renderer for directions and bind it to the map.
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow;
// Display the route between the initial start and end selections.
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
// Listen to change events from the start and end lists.
var onChangeHandler = function() {
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService,
markerArray, stepDisplay, map) {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Retrieve the start and end locations and create a DirectionsRequest using
// WALKING directions.
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: google.maps.TravelMode.WALKING
}, function(response, status) {
// Route the directions and pass the response to a function to create
// markers for each step.
if (status === google.maps.DirectionsStatus.OK) {
document.getElementById('warnings-panel').innerHTML =
'<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response, markerArray, stepDisplay, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function showSteps(directionResult, markerArray, stepDisplay, map) {
// For each step, place a marker, and add the text to the marker's infowindow.
// Also attach the marker to an array so we can keep track of it and remove it
// when calculating new routes.
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = markerArray[i] = markerArray[i] || new google.maps.Marker;
marker.setMap(map);
marker.setPosition(myRoute.steps[i].start_location);
attachInstructionText(
stepDisplay, marker, myRoute.steps[i].instructions, map);
}
}
function attachInstructionText(stepDisplay, marker, text, map) {
google.maps.event.addListener(marker, 'click', function() {
// Open an info window when the marker is clicked on, containing the text
// of the step.
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
Html side :
<input id="start" class="controls" type="text"
placeholder="picup lock">
<input id="end" class="controls" type="text"
placeholder="drop off">

Based from this documentation, error NOT_FOUND indicates at least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded.
Make sure that point1 and point3 are not empty. The API doesn't know how to create a route from "" to "".
Check this related ticket and tutorial.

I had the same issue yesterday, using the API via C# httpClient. But the same request worked fine in a browser. After a bit of debugging I found out that it only worked if I sent Accept-Language header in the httpClient…

Related

How to request directions from current location to destination using Google Maps JavaScript API

I've been exploring Google Maps JavaScript API for web and I am getting stuck trying to display directions between the user's current location and a destination.
I am able to display directions between two locations when they are predefined using LatLng(lat, lng). I am also able to find the current location of a user. I just can't seem to do both.
function initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
else {
alert("Geolocation not supported");
}
}
function locationSuccess(position) {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var trafficLayer = new google.maps.TrafficLayer();
var myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var LA = new google.maps.LatLng(34.0522, -118.2437);
var mapOptions = {
zoom: 8,
center: {lat: 34.2805, lng: -119.2945}
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
trafficLayer.setMap(map);
//This will mark the current location if found
// var myLocationMarker = new google.maps.Marker({
// position: myLocation,
// map: map,
// title: 'Current location'
// });
map.setCenter(myLocation);
var request = {
origin: myLocation,
destination: LA,
travelMode: 'DRIVING'
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK)
directionsDisplay.setDirections(result);
});
}
function locationError() {
alert("Couldn't get location");
}
I'm not sure what the issue was that was preventing you from realising your goals - I tried the code above and it appeared to work - as it was too cold to work in the garage I had a little play and created a small demo; perhaps though you or someone else might find the following useful?
Initially when the call to navigator.getCurrentLocation resolves with the user's location the map loads using the returned position object to form the map centre location. The route to the pre-defined destination is then calculated using the Directions service with a modified options parameter - notably in this instance to hide the default markers. The reason for hiding the markers is because they do not expose any events and thus we cannot bind any listeners to them so we add our own. The added markers allow the route to be dynamically re-calculated ( can also drag the actual route itself )
The text version of the directions is available by clicking on one of the two markers.
The destination is in Birmingham, UK. If you are outwith the UK this might not work immediately without editing this location. Also, a valid API key is required.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps: Directions from my location to...</title>
<meta charset='utf-8' />
<style>
body,
html { height:100%;margin:0;padding:0;box-sizing:border-box; }
#map { width:100%;height:100vh; margin:auto;float:none; }
#info{ display:none;padding:0.25rem;margin:1rem;background:white;font-size:0.75rem!important; }
</style>
<script>
let map;
let marker;
let infoWindow;
let oDir;
let oTraf;
let oDisp;
let oReq;
let destination={ lat:52.477068, lng:-1.911663 };
const modes={
walk:'WALKING',
bike:'BICYCLING',
car:'DRIVING',
pub:'TRANSIT'
};
const advReqOptions={
provideRouteAlternatives:true,
optimizeWaypoints:true,
avoidFerries:true,
avoidHighways:false,
avoidTolls:false
};
function initMap(){
/* utility to add a new marker and assign listeners to it */
const addmarker=function( pos, type, colour ){
marker=new google.maps.Marker({
icon:'//maps.google.com/mapfiles/ms/icons/'+colour+'-pushpin.png',
type:type,
draggable:true,
position:pos,
map:map
});
google.maps.event.addListener( marker, 'click', function(e){
infoWindow.getContent().style.display='block';
infoWindow.setPosition( this.getPosition() );
infoWindow.open( map );
});
google.maps.event.addListener( marker, 'dragend', calculateroute );
};
/* callback function when markers are dragged and the route is re-calculated */
const calculateroute=function(e){
oReq={
origin:this.type=='start' ? e.latLng : oReq.origin,
destination:this.type=='finish' ? e.latLng : oReq.destination,
travelMode:modes.car
};
oDir.route( Object.assign( oReq, advReqOptions ), callback );
};
/* process the route response */
const callback=function(r,s){
if( s === 'OK' ) oDisp.setDirections( r );
else evtGeoFailure( s );
}
/* Main callback invoked when the user's location has been identified */
const evtGeoSuccess=function(p){
/* create the map */
let location={
lat: parseFloat( p.coords.latitude ),
lng: parseFloat( p.coords.longitude )
};
let options= {
zoom: 16,
center:location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
let routeoptions={
suppressMarkers:true,
draggable:true,
map:map
};
/* create the map object */
map = new google.maps.Map( document.getElementById('map'), options );
/* add draggable markers to the start and end of pre-defined route */
addmarker( location, 'start', 'grn' );
addmarker( destination, 'finish', 'red' );
/* display the textual directions in an infowindow which opens on marker click */
infoWindow = new google.maps.InfoWindow({ maxWidth:450, disableAutoPan:false });
infoWindow.setContent( document.getElementById('info') );
/* create the objects required for the directions calculations */
oDir=new google.maps.DirectionsService();
oDisp=new google.maps.DirectionsRenderer( routeoptions );
oTraf=new google.maps.TrafficLayer();
/* construct the initial request */
oReq={
origin:location,
destination:destination,
travelMode:modes.car
};
/* go get the directions... */
oDisp.setMap( map );
oTraf.setMap( map );
oDisp.setPanel( infoWindow.getContent() );
oDir.route( Object.assign( oReq, advReqOptions ), callback );
};
const evtGeoFailure=function(e){ console.info( 'you broke the internets: %s', e ) };
const config={ maximumAge:60000, timeout:5000, enableHighAccuracy:true };
if( navigator.geolocation ) navigator.geolocation.getCurrentPosition( evtGeoSuccess, evtGeoFailure, config );
}
</script>
<script src='//maps.googleapis.com/maps/api/js?key=<<APIKEY>>&callback=initMap' async defer></script>
</head>
<body>
<div id='map'></div>
<div id='info'></div>
</body>
</html>

How to add live location tracking in ionic app

I want to add functionality like gmap navigation into ionic hybrid application like blue dot pointer also. Previously I used geolocation API but Location is not changed when I change my position (I seem static). I want to add the live location tracking like google map. Can anyone suggest me the right way?
Use watchPosition and change marker on map. Something like:
var myMarker = null;
// get current position
navigator.geolocation.getCurrentPosition(showPosition);
// show current position on map
function showPosition(position) {
myMarker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: new google.maps.Map(document.getElementById("map")),
icon: 'img/icons/myicon.png'
});
}
// watch user's position
navigator.geolocation.watchPosition(watchSuccess, watchError, watchOptions);
// change marker location everytime position is updated
function watchSuccess(position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// set marker position
marker.setPosition(latLng);
}
You can also use $cordovaGeolocation plugin. Take a look at plugin docs.
getCurrentPosition returns current position of Geolocation
watchPosition returns current position every time it changes. So, with this function, you can change the marker on map everytime with setPosition and pass coordinates to it.
You can just apply to your map property the native method setMyLocationEnabled(true).
See my example:
let element: HTMLElement = document.getElementById('map');
this.map = this.googleMaps.create(element);
this.map.setMyLocationEnabled(true);
This last line will active a native current position marker.
in my case, it can not find watchSuccess, watchError, watchOptions here is my code
if (navigator.geolocation.watchPosition(watchSuccess, watchError, watchOptions)) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
that.MyLocation = new google.maps.LatLng(pos);
}, function() {
});
} else {
// Browser doesn't support Geolocation
}
directionsService.route({
origin: this.MyLocation,
destination: this.Destination,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
// watch user's position
// change marker location everytime position is updated
watchSuccess(position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// set marker position
marker.setPosition(latLng);
}

Google Maps V3 autocomplete input jquery Mobile

I'm trying to get the autocomplete to work on a simple input text box. I have it working for one text box, but I have a second (to and from location) which it is throwing errors.
My code isn't very streamlined I don't think and I'm wondering if there is a cleaner method to get this working. I think my repetitive code maybe part of the problem. The 'to' input box doesn't work and no errors are thrown.
<script type="text/javascript">
$(document).on("pageinit", "#map_page", function () {
initialize();
layersOFFonload();
});
$(document).on('click', '#getDirectionsSubmit', function (e) {
e.preventDefault();
calculateRoute();
});
$(document).on('click', '#getCurrentLoc', function (e) {
e.preventDefault();
findCurrentPosition();
});
var directionDisplay,
directionsService = new google.maps.DirectionsService(),
map;
var geocoder = new google.maps.Geocoder();
var transitRoutesLayerKML = [];
var placeSearch, autocomplete;
function initialize() {
// set the default center of the map
var mapCenter = new google.maps.LatLng(55.1669513, -118.8031093);
// set route options (draggable means you can alter/drag the route in the map)
var rendererOptions = { draggable: true };
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
//updateMapSize(mapCenter);
// set the display options for the map
var myOptions = {
mapTypeControl: false,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mapCenter
}
// add the map to the map placeholder
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// bind the map to the directions
directionsDisplay.setMap(map);
// point the directions to the container for the direction details
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
// add a marker to the map on the geolocated point
marker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
//draggable: true,
map: map
});
var kmlOptions = {
suppressInfoWindows: false,
preserveViewport: true,
map: map
};
transitRoutesLayerKML[0] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route1.kml', kmlOptions);
transitRoutesLayerKML[1] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route2.kml', kmlOptions);
transitRoutesLayerKML[2] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route3.kml', kmlOptions);
transitRoutesLayerKML[3] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route4.kml', kmlOptions);
transitRoutesLayerKML[4] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route5.kml', kmlOptions);
transitRoutesLayerKML[5] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route6a.kml', kmlOptions);
transitRoutesLayerKML[6] = new google.maps.KmlLayer('http://mysite/KML/transit_mobile_route6b.kml', kmlOptions);
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(/** #type {HTMLInputElement} */(document.getElementById('from')), (document.getElementById('to')), { types: ['geocode'] });
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function () {
fillInAddress();
});
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (addressType) {
var val = place.address_components[i][addressType];
document.getElementById(addressType).value = val;
}
}
}
function findCurrentPosition() {
if (navigator.geolocation) {
// when geolocation is available on your device, run this function
navigator.geolocation.getCurrentPosition(foundYou, notFound);
autocomplete.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
} else {
// when no geolocation is available, alert this message
alert('Geolocation not supported or not enabled.');
}
}
function foundYou(position) {
// convert the position returned by the geolocation API to a google coordinate object
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// then try to reverse geocode the location to return a human-readable address
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// if the geolocation was recognized and an address was found
if (results[0]) {
// this will update the position of the marker
marker.setPosition(latlng);
// compose a string with the address parts
var address = results[0].address_components[0].long_name + ' ' + results[0].address_components[1].long_name + ', ' + results[0].address_components[3].long_name
// set the located address to the link, show the link and add a click event handler
// onclick, set the geocoded address to the start-point formfield
//$('#from').text(address);
$('#from').val(address);
// call the calcRoute function to start calculating the route
}
} else {
// if the address couldn't be determined, alert and error with the status message
alert("Geocoder failed due to: " + status);
}
});
}
<div id="fromlocationField" data-role="my-ui-field-contain">
<input type="text" id="from" placeholder="From Address, (eg, 10205 - 98street)" value="" /><button id="getCurrentLoc" data-icon="star">Use Current Location</button>
</div>
<div id="tolocationField" data-role="my-ui-field-contain">
<input type="text" id="to" placeholder="To Destination (eg, 10205 - 98street)" value="" />
</div>
<a data-icon="search" data-role="button" href="#" id="getDirectionsSubmit">Get directions</a>
I tried a different method of populating a autocomplete but couldn't get it to resolve at all. This is the closes I've gotten it to work, it works on the 'from' input, but not the 'to' input.
Any advice would be greatly appreciated.
Thanks!
I changed my approach. Since I already have all the geocode information in the application I really just wanted to populate the text boxes. I added this code to the initialize function which does as I would like.
var inputStart = document.getElementById('from');
var inputDestination = document.getElementById('to');
var options = {componentRestrictions: {country: 'ca'}};
new google.maps.places.Autocomplete(inputStart, options);
new google.maps.places.Autocomplete(inputDestination, options);

Google Places API, additional marker (manually added) to results

My javascript isn't too hot, I'm trying to add a manual marker onto a number of locations gathered from the Google Places API.
I followed this post to get to my following code (with a few amendments):
<script type="text/javascript">
var map;
var infowindow;
var service ;
base_Icon_festival = "https://maps.gstatic.com/mapfiles/ms2/micons/volcano.png";
shadow_festival = "https://maps.gstatic.com/mapfiles/ms2/micons/volcano.shadow.png";
function initialize(lat,lng)
{
var origin = new google.maps.LatLng(lat,lng);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.HYBRID,
center: origin,
zoom: 14,
scrollwheel: false,
});
var request = {
location: origin,
radius: 2500,
types: ['train_station','bus_station','subway_station','airport']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
base_Icon_train = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
base_Icon_bus = "http://maps.google.com/mapfiles/ms/icons/green-dot.png";
base_Icon_subway = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png";
base_Icon_airport = "http://maps.google.com/mapfiles/ms/icons/yellow.png";
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker;
var icon_to_use;
if (place.types.indexOf('train_station') != -1) {
icon_to_use = base_Icon_train;
} else if (place.types.indexOf('bus_station') != -1) {
icon_to_use = base_Icon_bus;
} else if (place.types.indexOf('subway_station') != -1) {
icon_to_use = base_Icon_subway;
} else if (place.types.indexOf('airport') != -1) {
icon_to_use = base_Icon_airport;
}
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon_to_use
});
var content='<strong style="font-size:1.2em">'+place.name+'</strong>'+
'<br/><strong>Latitude: </strong>'+placeLoc.lat()+
'<br/><strong>Longitude: </strong>'+placeLoc.lng()+
'<br/><strong>Type: </strong>'+place.types[0];
//make a request for further details
service.getDetails({reference:place.reference}, function (place, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK)
{
more_content='<hr/><strong>Details';
if(place.website)
{
more_content+='<br/><br/><strong>'+place.website+'';
}
}
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content+more_content);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', function(){initialize(<?php echo $coordinated; ?>);});
</script>
<div id="map" style="height:400px;"></div>
Now I would like to manually add another marker which is located at the center of the map (ie, the variable origin which is currently being pulled from a PHP variable - var origin = new google.maps.LatLng(lat,lng);). I also need this marker to have a different icon associated with it (base_Icon_festival and shadow_festival respectively).
I'm not sure how to manually add another marker to the ones already gathered by the places API?
End goal: have a festival icon marker at the center of the map and a number of public transport markers surrounding it, resulting code to go on individual festival pages of a website.
Thanks in advance to anyone who can help.
In the Google Maps API, markers are added to the map by creating a Marker object and setting the map property. This is the snippet in your code that adds the existing Markers.
marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon_to_use
});
To add a new marker you would just replace the position and icon properties with your values.
new google.maps.Marker({
map: map,
position: origin,
icon: shadow_festival
});
This code can probably be added at the end of the Callback function and if you don't need the actual marker object for anything else, you can just create the Marker object and never assign it.
There is an example from the Google Maps API docs here.

how to open popup on click of a marker from the directions service?

UPDATE
when i click green marker,it's display address of location.can i change it?
LATER EDIT :
is it possible to open popup on click of a marker from the directions service?
or try the other way like only hide a marker from the directions service(green marker) and display only red marker(hide only green marker not it's route)?is it good way?
if not possible, please suggest some alternative ideas.
OLDER:
i have a two types of marker on google map.the red marker is normal marker which represent location.and green marker is route marker(its represent many of waypoints of the map).
I modify the infowindow with textbox.which is open on click red marker.
actually i am trying to do is, first i place multiple markers on google map then i draw route between this markers.this thing is done.reminder thing is on click green marker one popup is opened in which user enter price and then click the button.then i got this value and store it to database.
the problem is:
(1) how to open same infowindow on click of green marker?
in short,how to write a code for display infowindow on click of of green marker.
how to find click event of green marker?
code is:
<script type="text/javascript">
var markerarray=new Array();
//for way points
var waypts=[];
//array in json format for placing multiple marker
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
<!-- ************* for placing markers ************ -->
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map //enable if you want marker
});
//push value into way points
waypts.push({
location:locations[i][0],
stopover:true
});
//create array for polyline
markerarray[i] = marker.getPosition();//(Array(locations[i][5], locations[i][6]));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var data='<div style="height:150px !important"><table><tr><td>Enter Price</td></tr><tr><td><input type="text" name="prc" id="prc" /></td></tr></table></div>';
infowindow.setContent(data);
infowindow.open(map, marker);
}
})(marker, i));
}
<!-- ************** for route between markers ******************* -->
var first=locations[locations.length-1][0];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: 'red',//"black",
strokeOpacity: 1.0,
strokeWeight: 3
}
});
var start = locations[0][0];//"Bopal, Ahmedabad, Gujarat, India";
var end = locations[locations.length-1][0];//"Nikol, Ahmedabad, Gujarat, India";
//remove start destination from array
waypts.shift();
//remove end destination from array
waypts.pop();
var request = {
origin:start,
destination:end,
waypoints:waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
</script>
Thanks in advance.
It is not impossible but it will take some time for code, The way is if you are using for mobile device then you need to accelerator from your device and call geolocation function on position change I think you understand and the second method is from purely javascript method for that you need to call your geolocation function within set Interval understand also draw line separately from marker your marker function only calls within set Intervals for getting your current location with infowindow. Example is :
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//keep this in setInterval
// Try HTML5 geolocation
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: 'Location found using HTML5.'
});
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);
}
//close here your set interval
google.maps.event.addDomListener(window, 'load', initialize);
It's possible. You can hide the default marker such that you can build a custom marker on the clicked location. This code is to hide the marker.
var rendererOptions = {
suppressMarkers : true
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

Categories