resize google maps not working and takes long time - javascript

At first, my problem was that the google maps with direction service was not loading correctly. After some researches, i find google.maps.event.trigger(map, 'resize'). Ok, now it works. Kinda.
The order of my app is: page x, page A with the map and the direction, page y, page B with the map and the direction.
My script is:
function initialize(mapa_id) {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 17,
mapTypeControl: false,
zoomControl: false,
draggable: false,
center: new google.maps.LatLng(-23.583693,-48.042186),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById(mapa_id), mapOptions);
google.maps.event.trigger(map, 'resize');
directionsDisplay.setMap(map);
if(mapa_id == 'map-canvas'){
navigator.geolocation.getCurrentPosition(rotaInicial, onError, options);
}else{
directionsDisplay.setMap(map);
navigator.geolocation.getCurrentPosition(rotaFinal, onError, options);
}
}
function rotaInicial(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var start = new google.maps.LatLng(latitude,longitude);
var end = new google.maps.LatLng(-23.578659,-48.038045);
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
google.maps.event.trigger(map, 'resize');
directionsDisplay.setDirections(response);
}
});
}
function rotaFinal() {
var start = new google.maps.LatLng(-23.578659,-48.038045);
var end = new google.maps.LatLng(-23.585503,-48.038324);
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
google.maps.event.trigger(map, 'resize');
directionsDisplay.setDirections(response);
}
});
}
So, what happens now: the page A loads the map first (correctly and with no directions) and then after a few seconds (5 - 8) the 'resize' happens and it shows the directions. Then it goes to page y, after click the button it goes to the page B and the map appears only on the top left. After a few seconds again, the 'resize' happens and show the directions. when i do this routine again (back to page x), the first map loads also in top left and it happens all those things.
I have two problems.
When the page loads, i want to show the map already with directions.
If is not possible ok, but at least it should load the map correctly. And this resize should work faster.
I'm not sure if i put the 'resize' code in the right place. Any ideas?

you call both functions that will draw the route(rotaInicial & rotaIFinal) in the success-callback of navigator.geolocation.getCurrentPosition . getCurrentPosition will be executed asynchronously and it may take some time till you get a result.
Therefore, as long as you need to set the direction based on the users location, there isn't anything you can do to speed-up the drawing of the directions.

Related

Draggable markers on Google transit map

I'm trying to create a transit map (with bus/metro indications) using Google Maps, but when I create the "start" and "end" markers from inputs (with autocomplete addresses), there's no way to drag any marker despite set drag option as true.
Changing the travelMode option to google.maps.TravelMode.DRIVING the draggin' is enabled. And going back this property to google.maps.TravelMode.TRANSIT the daggin' goes back to disabled.
There's a way to solve this issue?
Code:
var directionsService;
var directionsDisplay;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: -32.89, lng: -68.845} // Mendoza.
});
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
var addresses = directionsDisplay.getDirections().routes[0].legs[0];
document.getElementById('from').value = addresses.start_address;
document.getElementById('to').value = addresses.end_address;
});
google.maps.event.addDomListener(document.getElementById('go'), 'click', displayRoute);
var input_from = document.getElementById('from');
var autocomplete = new google.maps.places.Autocomplete(input_from);
autocomplete.bindTo('bounds', map);
var input_to = document.getElementById('to');
var autocomplete = new google.maps.places.Autocomplete(input_to);
autocomplete.bindTo('bounds', map);
displayRoute();
}
function displayRoute() {
directionsService.route({
origin: document.getElementById('from').value,
destination: document.getElementById('to').value,
//travelMode: google.maps.TravelMode.DRIVING,
travelMode: google.maps.TravelMode.TRANSIT
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
console.log(response);
directionsDisplay.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initMap);
Unfortunately, the "draggable" mode is not permited to the TRANSIT travel mode. Just now I'm trying to find a way and I found your question by the way.
EDIT
As the google documentation says:
Users may modify cycling, walking or driving directions displayed
using a DirectionsRenderer dynamically if they are draggable, allowing
a user to select and alter routes by clicking and dragging the
resulting paths on the map. You indicate whether a renderer's display
allows draggable directions by setting its draggable property to true.
Transit directions cannot be made draggable.
Check it here: https://developers.google.com/maps/documentation/javascript/directions#TransitOptions
We will have to find another way... if I find it I'll make you know, if you find it first I'll be grateful if you told me.
The "solution" (hack) I found, using trial and error, is to prevent to show the markers the API creates:
var directionsDisplay = new m.DirectionsRenderer({
suppressMarkers: true, // Supressing the default markers
map: map,
// another options...
});
And implement my own function to show markers:
function placeMarker(e, t) {
t < 2 && (markers[t] = new m.Marker({
position: e,
draggable: true, // YES! It's draggable!
map: map
}), m.event.addListener(markers[t], "dragend", function() {
geocodePosition(markers[t].getPosition(), t);
}), markers[t].setVisible(true), geocodePosition(markers[t].getPosition(), t), arrangeBounds());
}
Then, the markers are draggable using a Google transit map... The solution is late but, I hope, not least.

Google Maps Javascript API, Direction Update with Geolocation Move

I created simple app that, get users current position and the destination and set direction through the google map javascript api.
Sample code:
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map(document.getElementById('maps'),
mapOptions);
directionsDisplay.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
var lat = position.coords.latitude; //get the current position
var lon = position.coords.longitude;
var request = {
origin: new google.maps.LatLng(lat, lon), //set the position
destination: "colombo", //set the destination
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response); //set the direction in google map
}
});
Question:
Now i want to update the direction dynamically based on current location when user move the device. ( like android google maps app )
Is google api support that kind of stuff.
Is there anyway to do it without re-run the js again.

Google Maps resize css display none

This question has been asked many times here, and that is that Google Maps display partially. My problem is: I use waypoints to trigger CSS3 animations on my page. On the page with Google Maps I have set the CSS to display: none; until the waypoint is hit. This causes Google Maps to break.
From my research and a search done on Stack Overflow, the fix is this (correct me if I am wrong):
google.maps.event.trigger(map, 'resize');
Here is my JavaScript code that I have gotten from another developer online, I have no idea where to put the Google Maps resize trigger?:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var latlng = new google.maps.LatLng(-33.8333406,18.6470022);
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map"),myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"Get Directions"
});
}
function calcRoute() {
var start = document.getElementById("routeStart").value;
var end = "-33.8333406,18.6470022";
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);
} else {
if (status == 'ZERO_RESULTS') {
alert('No route could be found between the origin and destination.');
} else if (status == 'UNKNOWN_ERROR') {
alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
} else if (status == 'REQUEST_DENIED') {
alert('This webpage is not allowed to use the directions service.');
} else if (status == 'OVER_QUERY_LIMIT') {
alert('The webpage has gone over the requests limit in too short a period of time.');
} else if (status == 'NOT_FOUND') {
alert('At least one of the origin, destination, or waypoints could not be geocoded.');
} else if (status == 'INVALID_REQUEST') {
alert('The DirectionsRequest provided was invalid.');
} else {
alert("There was an unknown error in your request. Requeststatus: \n\n"+status);
}
}
});
}
Here is waypoints jquery code that triggers display: block
// Studio Page
jQuery('.studio-page').waypoint(function() {
jQuery('.kickass-studio').addClass( 'show animated bounceInLeft' );
jQuery('.location').addClass( 'show animated bounceInRight' );
jQuery('.geo-address').addClass( 'show animated bounceInDown' );
},
{
offset: '10%'
});
Just add it at the end of initialize function....
Also you need to save the map object in a variable and call the resize event again when you make the css of the google maps to display: block with this map object

dynamic route with Google directions API

Initially I have two points on map. One of them being origin and other being destination.
The origin is dragable while destination is fixed.
When drawing the map for first time after page load, I have some default value for origin, while destination point gets value from database.Initial Loading works fine. I am able to draw route between origin and destination.
I draw directions on map using this below function
function calcRoute() {
var request = {
origin:myLatLng1,
destination:myLatLng,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Now I have a event listener whenever my origin marker is draged, it gets the new latlong of the new position of orign marker, then I call the same function above to get new route.
function togglePos(){
myLatLng1 = new google.maps.LatLng(marker1.getPosition());
calcRoute();
}
This is where I am facing problem, I am not able to redraw new route between the new marked origin and the same old destination.
This is my initialize function if any1 needs it.
function initialize() {
var mapOptions = {
zoom: 13,
center: myLatLng
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
directionsDisplay.setMap(map);
var image = 'myimage.png';
marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
});
marker1 = new google.maps.Marker({
position: myLatLng1,
map: map,
draggable: true
});
google.maps.event.addListener(marker1, 'dragend', togglePos);
calcRoute();
}
I am not getting any javascript error.
I am building something like this.
https://developers.google.com/maps/documentation/javascript/examples/directions-simple
But instead of selecting it from drop down box, I am calling the function when marker is moved.
Fiddle link: http://jsfiddle.net/FvqAL/4/
But i have no idea why its not working on fiddle :|
I made some changes in calc route, now whenever it is called, it get marker1 position and draw route through it.
function calcRoute() {
var request = {
origin:marker1.getPosition(),
destination:myLatLng,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Here is final fiddle if you want to check it out.
Thanks for helping :)

Google maps v3: adding a new map when function 'failure' called

On the contact page of my site two things can happen:
The user has geolocation enabled, and a map (map-canvas) will display a route from their location to a predefined location dest. This feature works fine.
The user doesn't have geolocation enabled or chooses not to allow it. An alert will show (works fine), and some text will be added to the directions-panel (works fine). The third thing I want to happen in this scenario is a new map be added to map-canvas that is centred on dest, this feature doesn't seem to be working and I can't figure out why.
Code below should give a good representation of the above:
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var dest = "Unit 20, Tallaght Business Centre, Whitestown Road, Tallaght Business Park, Ireland";//53.282882, -6.383155
var ourLocation = {lat : 53.282882, lng : -6.383155}//centre attribute of the map must be a LatLng object and not hardcoded as above
function initGeolocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition( success, failure );
}
}
//create a new map centered on user's location, display route and show directions
function success(position) {
directionsDisplay = new google.maps.DirectionsRenderer();
coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directions-panel"));
calcRoute();
}
//calculate the route from user's location to 'dest'
function calcRoute() {
var start = coords;
var end = dest;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
//tell user geoloc isn't enabled and just plot 'ourLocation' on 'map-canvas'
function failure() {
alert("Your browser does not have geolocation enabled so we can't give you directions to our office. Enable geolocation and try again, or consult the map for our address.");
$("#directions-error-message").css({
visibility: 'visible'
});
var destMapOptions = {
zoom:13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(ourLocation.lat, ourLocation.lng)
}
map = new google.maps.Map(document.getElementById("map-canvas"), destMapOptions);
}
</script>
Anyone have any ideas why this isn't working? All help appreaciated.
EDIT: Working version above
You need to pass the map a LatLng object for it's centre, not an address. You will need to use Googles LocalSearch services to make that work.
var dest = {
lat : 53.282882,
lng : -6.383155
}
var destMapOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(dest.lat,dest.lng)
}
Also, as you have map declared as a var already maybe use that rather than a function scoped variable for the map.
The center attribute of the map options must be a LatLng object. You've got it hardcoded as an address string.

Categories

Resources