i use that code to have the geolocation in my app and it works good also when i'm moving. I added some few lines to create a calculation from the geolocation to an end (fixed) point with fixed lat-long. I don't understand why the origin point in my code is not accepted (fireBug says that i cannot call a property [object Object] on it) but i cannot figure out.
Here are the code about the gmaps v3:
//image for the marker
var imageLoc = '../../img/bbb3.gif'
var map;
//initialize the maps
function initialize() {
//call directionsService and Display for the route
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
//map option
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(44.49489, 11.34262),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
//create the marker for the geolocation
marker = new google.maps.Marker({
map: map,
icon: imageLoc
});
//call updatePos() function
updatePos();
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
//origin is the marker of my geolocation
origin: marker,
//destination is a fxed position
destination: new google.maps.LatLng(44.496099,11.340246),
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
var i;
//here I set my marker (if i==0 -> first run)
function updatePos(){
var options = {
timeout: 60000, enableHighAccuracy: true
};
var myUpdatedPos = navigator.geolocation.watchPosition(onSuccess, onError, options);
function onSuccess(position) {
if (i==0){
marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map
});
}
i++;
//here I update the position
newLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
marker.setPosition(newLatlng);
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Does anyne have idea why?
kind regards
Brus
The directionRequest takes either a string (an "address") or a google.maps.LatLng for origin and destination. marker is a google.maps.Marker object.
var request = {
//origin is the marker of my geolocation
origin: marker,
//destination is a fxed position
destination: new google.maps.LatLng(44.496099,11.340246),
travelMode: google.maps.DirectionsTravelMode.WALKING
};
To get the position of a marker, use its getPosition method:
var request = {
//origin is the marker of my geolocation
origin: marker.getPosition(),
//destination is a fxed position
destination: new google.maps.LatLng(44.496099,11.340246),
travelMode: google.maps.DirectionsTravelMode.WALKING
};
To give the marker a position when you initialize it, you can do this:
//create the marker for the geolocation
marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: imageLoc
});
Related
See this image.
I try to show my current location to the destination but the direction does not show up in the map, it just show the route at panel only.
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
var trafficLayer = new google.maps.TrafficLayer();
var mapOptions =
{
zoom: 15,
center: coords
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
displayRoute(directionsService, directionsDisplay);
function displayRoute(service, display) {
service.route({
origin: coords,
destination: new google.maps.LatLng(5.409722, 100.313319),
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
});
The map does not show the direction from my current location to destination.
When you create your google.maps.DirectionsRenderer, the map is undefined. Either create the google.maps.DirectionsRenderer after the map, or call .setMap on it once the map is defined.
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService;
var trafficLayer = new google.maps.TrafficLayer();
var mapOptions = {
zoom: 15,
center: coords
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
displayRoute(directionsService, directionsDisplay);
proof of concept fiddle
code snippet:
var geocoder;
var map;
// [ 0 ]: Tapah, Perak, Malaysia (4.19773, 101.261529)
function initialize() {
var latitude = 4.19773;
var longitude = 101.261529;
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService;
var trafficLayer = new google.maps.TrafficLayer();
var mapOptions = {
zoom: 15,
center: coords
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
displayRoute(directionsService, directionsDisplay);
function displayRoute(service, display) {
service.route({
origin: coords,
destination: new google.maps.LatLng(5.409722, 100.313319),
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
<div id="right-panel"></div>
After reading documentation for the SearchBox class, the Places library including the AutoComplete class, and the Directions service, I cannot figure out how to pass the address selected by a user from the SearchBox to the Directions service to draw the map. The map and marker display correctly, and the SearchBox displays and functions correctly. On the "place_change" event, though, nothing happens. My code:
var rawlatitude = <?php echo $loc_lat; ?>;
var rawlongitude = <?php echo $loc_long; ?>;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude,longitude);
google.maps.event.addDomListener(window, 'load',initMap(latitude,longitude));
function initMap(lat,lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// listen to and respond to address search
var onChangeHandler = function() {
var location = searchBox.getPlaces();
var start = location.place_id;
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'place_change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: start,
destination: latlong,
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);
}
});
}
As Dr.Molle observed in his comment,
There is no place_changed-event for a SearchBox, it's an event for Autocomplete. The event for a SearchBox is called places_changed.
Also note that a SearchBox.getPlaces() returns an array with places
working fiddle
working code snippet:
var rawlatitude = 40.7127837;
var rawlongitude = -74.0059413;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude, longitude);
var viewport = {
"south": 40.4960439,
"west": -74.2557349,
"north": 40.91525559999999,
"east": -73.7002721
};
google.maps.event.addDomListener(window, 'load', function() {
initMap(40.735657, -74.1723667);
});
function initMap(lat, lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
draggable: true,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: viewport
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// listen to and respond to address search
var onChangeHandler = function() {
var locations = searchBox.getPlaces();
var start = locations[0].place_id;
var bounds = new google.maps.LatLngBounds();
bounds.extend(latlong);
bounds.extend(locations[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
position: locations[0].geometry.location,
map: map,
title: locations[0].name
})
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'places_changed', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: {
placeId: start
},
destination: {
location: latlong
},
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);
}
});
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" />
<div id="map"></div>
I am displaying google map with code below, I want to hide Polyline between A to B. All answers on google talk about creating an array and then doing array.setmap(null). can I hide polyline without using arrays. In other case, how should I use array to hide polyline using code below.
Edit: I need marker A and B to be shown
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var time;
function initialize() {
var rendererOptions = {
map: map,
draggable: true
}
// Instantiate a directions service.
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// Create a map and center it on islamabad.
var islamabad = new google.maps.LatLng(33.7167, 73.0667);
var mapOptions = {
zoom: 13,
center: islamabad
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = document.getElementById('MainContent_txtFrom').value;
var end = document.getElementById('MainContent_txtTo').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
If you want to render the directions but hide the polyline, use the DirectionsRendererOptions suppressPolylines.
function initialize() {
var rendererOptions = {
suppressPolylines: true,
map: map,
draggable: true
}
// Instantiate a directions service.
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
As shown in the demo below, you can remove polylines by two means:
setting the option suppressPolylines to true in directionsDisplay, your google.maps.DirectionsRenderer by using
directionsDisplay.setOptions({
suppressPolylines: true
});
This will preserve the start- and end-point markers.
The method setOptions(options:DirectionsRendererOptions) changes the options settings of DirectionsRenderer after initialization.
use directionsDisplay.setMap(null); to remove all directions rendering, but this includes markers, so if you do that you will need to add extra markers to the map.
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var time;
var pointA = new google.maps.LatLng(48.86, 2.35);
var pointB = new google.maps.LatLng(33.7167, 73.0667);
function initialize() {
var rendererOptions = {
map: map,
draggable: true
}
// Instantiate a directions service.
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// Create a map and center it on islamabad.
var islamabad = new google.maps.LatLng(33.7167, 73.0667);
var mapOptions = {
zoom: 13,
center: islamabad
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = pointA;
var end = pointB;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
};
function removeRoute() {
directionsDisplay.setOptions({
suppressPolylines: true
});
// this "refreshes" the renderer
directionsDisplay.setMap(map);
};
function removeRouteNull() {
directionsDisplay.setMap(null);
};
google.maps.event.addDomListener(window, 'load', initialize);
#map {
height: 280px;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<button onclick="removeRoute()">Remove route (suppressPolylines)</button>
<button onclick="removeRouteNull()">Remove route (setMap(null))</button>
<button onclick="initialize()">Undo all</button>
<section id="map"></section>
If you refer to this answer: Google Maps v3 directionsRenderer.setMap(null) not working to clear previous directions you should see what you're looking for.
You do not need to use an array as you're implementing the directionsRenderer object. If you declare this globally (Edit Which I now see you have already) (so that you only have one instance at any given time) then you can simply use directionsDisplay.setMap(null) to remove previous directions rendered.
If you want to render the markers from the response but hide the polyline I suppose the simplest (but I would imagine by no means cleanest) way would be to simply alter the opacity on the polyline object:
var myPolylineOptions = new google.maps.Polyline({
strokeColor: '#FF0000',
strokeOpacity: 0.00001,
strokeWeight: 0
});
And then assign it to your renderer:
directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions: myPolylineOptions});
I have a google map on a website where I show the position of a business with a custom marker, also, I show the routes to get to the place but I can't seem to understand how to use a custom icon for the START position...
Here is the code I use:
<script>
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({draggable: true,suppressMarkers: true});
var latlng = new google.maps.LatLng(45.86140239,-74.062538);
var myOptions = {
zoom:13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng,
mapTypeControl: false,
panControl: false,
streetViewControl: false,
zoomControl: false,
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Marqueur sur le bureau
var icon = {url: 'marker001c.png'};
var headquartersMarker = new google.maps.Marker({
position: latlng,
map: map,
animation: google.maps.Animation.DROP,
icon: icon,
zIndex:99999
});
directionsDisplay.setMap(map);
}
// Calcule de la route
function calcRoute() {
var start = document.getElementById("start").value;
var end = new google.maps.LatLng(45.86140239,-74.062538);
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);
}
directionsDisplay.setPanel(document.getElementById('panel'));
});
var starticon = new google.maps.MarkerImage('test.png');
var marker = new google.maps.Marker({
position:start,
map: map,
icon: starticon,
});
makeMarker({
position: new google.maps.LatLng(60.17295,24.93981),
content: "Some text in the info bubble.",
title: "Tooltip text"
});
}
</script>
By using this code it show me the end icon (my main marker) but I can't change the start icon. Any idea?
start position as string could be used for DirectionsService but for marker you have to change position to LatLng.
See Geocoding Service
For geocoding add new global variable:
...
var map;
var geocoder;
And initialize it:
function initialize() {
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer({draggable: true, suppressMarkers: true});
...
And get the latlng of the start 'address' after directionsService.route():
geocoder.geocode( { 'address': start}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var starticon = new google.maps.MarkerImage('images/start.png');
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon: starticon
});
} else {
alert("Geocode failed with status: " + status);
}
});
See example at jsBin. Note: it won't work there because I use my icon images so put in paths to your icon images.
I want to locate a user's location using Geolocation and then navigate between user;s position and a fix point, but Google map just won't navigate and I am using the codes from Google's official documentation!
What's wrong? I am going mad after tried thousands of times,plz help
<script type="text/javascript">
$( "#map-page" ).live( "pageinit", function() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var salon = new google.maps.LatLng(22.981666,120.194301);
var defaultLatLng = new google.maps.LatLng(22.983587,120.22599); // Default to Hollywood, CA when no geolocation support
if ( navigator.geolocation ) {
function success(pos) {
// Location found, show map with these coordinates
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
calcRoute(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
console.log(error);
drawMap(defaultLatLng); // Failed to find location, show default map
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
} else {
drawMap(defaultLatLng); // No geolocation support, show default map
}
function drawMap(latlng) {
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Greetings!"
});
var marker = new google.maps.Marker({
position:new google.maps.LatLng(22.981666,120.194301),
map:map,
title:"the salon"
});
}
function calcRoute(latlng) {
var start = latlng;
var end = new google.maps.LatLng(22.981666,120.194301);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
});
</script>
You forgot to setup directionsDisplay.