Using geoPosition.js with colobox - javascript

I'm trying to create a colorbox link that ask the user for permission to detect his location, and if the user agree he gets a map with direction from his location.
Now I managed to make it work but not very well. In the first time when the user need to give permission the map loading perfectly, but in the second time when the permission already given the map not loading correctly.
my code:
function directionMap() {
var position;
jQuery('.direction-map').colorbox({
maxWidth: '100%',
maxHeight: '100%',
opacity: 0.5,
html: '<div id="map" style="width: 800px; height: 500px"></div>',
onLoad: function() {
var success = function(pos) {
var lat = pos.coords.latitude,
long = pos.coords.longitude,
coords = {lat: lat, lng: long};
var start = coords;
var target = {lat: 31.273257, lng: 34.797528};
var map = new google.maps.Map(document.getElementById('map'), {
center: start,
scrollwheel: false,
zoom: 7
});
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// Set destination, origin and travel mode.
var request = {
destination: target,
origin: start,
travelMode: google.maps.TravelMode.DRIVING
};
// Pass the directions request to the directions service.
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
directionsDisplay.setDirections(response);
}
});
}
var error = function() {
alert('Can\'t find your location');
}
if (geoPosition.init()) {
geoPosition.getCurrentPosition(success, error, {
enableHighAccuracy:true,
timeout: 1000
});
}
return false;
},
});
}
My jsFiddle

I found the solution.
The problem was that the map should load after the colorbox completed, but just if the permission for location was given. so I wrote it with "onclick" handler and load the colorbox in the success variable.
this is the code:
function directionMap() {
document.getElementById('get_location').onclick = function() {
var success = function(pos) {
jQuery('.direction-map').colorbox({
maxWidth: '100%',
maxHeight: '100%',
opacity: 0.5,
html: '<div id="map" style="width: 800px; height: 500px"></div>',
open: true,
onComplete: function() {
var lat = pos.coords.latitude,
long = pos.coords.longitude,
coords = {lat: lat, lng: long};
var start = coords;
var target = {lat: 31.273257, lng: 34.797528};
var map = new google.maps.Map(document.getElementById('map'), {
center: start,
scrollwheel: false,
zoom: 7
});
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// Set destination, origin and travel mode.
var request = {
destination: target,
origin: start,
travelMode: google.maps.TravelMode.DRIVING
};
// Pass the directions request to the directions service.
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
directionsDisplay.setDirections(response);
}
});
}
});
}
var error = function() {
alert('Can\'t find your location');
}
if (geoPosition.init()) {
geoPosition.getCurrentPosition(success, error, {
enableHighAccuracy:true,
timeout: 1000
});
}
return false;
}
}

Related

Google map Remove previous route and draw a new route

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>

Google Maps Marker Listeners

I've been trying to get listeners to function with GMaps but have been having some troubles. At the moment clicking on markers yields the address of the stop but does not call the handler. Also I'm mapping out markers using the directions service in case that might for whatever reason effect event-handling
Initializing...
function initialize() {
latlng = avgLatLng(load)
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
mapOptions = {
zoom : 10,
center : {lat : latlng['latitude'], lng : latlng['longitude']},
disableDefaultUI : true,
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
setMarkers(load);
calcRoute(load.stops)
}
Calculate route...
function calcRoute(stops) {
var markerLocs = [];
var travelMode = google.maps.TravelMode['DRIVING'];
for(var i=0; i<stops.length; i++) {
markerLocs.push({
location : new google.maps.LatLng(stops[i].latitude, stops[i].longitude),
stopover : (i==0 || i==stops.length ? false : true),
});
}
var request = {
origin: markerLocs[0].location,
destination: markerLocs[markerLocs.length-1].location,
waypoints: markerLocs.slice(1, (markerLocs.length-1)),
travelMode: travelMode,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
}
Set markers...
function setMarkers(load) {
for (var i = 0; i < load.stops.length; i++) {
var markerOptions = {
position: {'lat' : load.stops[i]['latitude'], 'lng' : load.stops[i]['longitude']},
map: map,
animation: google.maps.Animation.DROP,
title: load.stops[i]['city'],
zIndex: i,
clickable: false,
}
var marker = new google.maps.Marker(markerOptions);
google.maps.event.addDomListener(marker, 'mouseout', function() {
console.log('mouseover');
});
google.maps.event.addDomListener(marker, 'click', function() {
console.log('mouseover');
});
}
}
You have a trivial error in your code. In function function setMarkers(load), your markers are configured not to respond to click events:
clickable: false,
should be:
clickable: true,
You need to set clickable even to get mouseOver and MouseOut events.

Google maps API DirectionsService between lat and long and GeolocationMarker

I am trying to get the directions services working on google maps api v3.
It is a webapp for smartphones where the user can get directions from where they are (GeolocationMarker) to a static (hardcoded) location defined by a lat and long.
The map centres on the hard coded lat and long, and then I have an icon (gps.png) that onclick should calculate and plot the directions between the two points.
I am not overly strong in javascript and this is essentially a mashup of code...can anyone see what I have done wrong and why this wont work?
Javascript is:
<code>
var map, GeoMarker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var arena = new google.maps.LatLng(43.684782688659126,-79.2992136269837);
var mapOptions = {
zoom: 12,
center: arena,
panControl: false,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
directionsDisplay.setMap(map);
var marker1 = new MarkerWithLabel({
position: arena,
draggable: false,
raiseOnDrag: false,
map: map,
icon: "images/lax-pin1.png",
labelContent: "Ted Reeve Arena",
labelAnchor: new google.maps.Point(25, 0),
labelClass: "pin", // the CSS class for the label
labelStyle: {opacity: 0.95}
});
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
map.setCenter(e.latLng);
map.fitBounds(e.latLngBounds);
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
}
function calcRoute() {
var request = {
origin: GeoMarker,
destination: marker1,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</code>
The html is an onclick div tag for the calcRoute function
Thanks for any help....
There is an error reported:
TypeError: e is undefined
for line
map.setCenter(e.latLng);
Event listener
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
map.setCenter(e.latLng);
map.fitBounds(e.latLngBounds);
});
should be changed to
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
//map.setCenter(e.latLng);
//map.fitBounds(e.latLngBounds);
map.setCenter(GeoMarker.getPosition());
map.fitBounds(GeoMarker.getBounds());
});
request should be changed to:
var request = {
origin: GeoMarker.getPosition(),
destination: marker1.getPosition(),
travelMode: google.maps.TravelMode.DRIVING
};
because origin/destination expects string or valid LatLng
Update: I forgot this change: marker1 has to be changed to global:
var map, GeoMarker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var marker1;
Okay, I got it to work, but not pretty. This is what I did
function calcRoute() {
var arena1 = new google.maps.LatLng(43.684782688659126,-79.2992136269837);
var request = {
origin: GeoMarker.getPosition(),
destination: arena1,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});

Function to determine if geo-location is enabled

I have a function that determines if the users broswer is geo-location enabled and if the user has geo-location enabled it is to display a Google map, if it isn't it then displays a different map.
function init_maps() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo, { timeout: 20000 });
} else {
noGeoInfo();
}
function geoInfo(position) {
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();
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
directionsDisplay.setMap(map);
var request = {
origin: coords, //start point for directions
destination: '54.861283, -6.326805', //end point for directions
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
//}
function noGeoInfo() {
var location = new google.maps.LatLng(54.861283, -6.326805);
var mapOptions = {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
marker = new google.maps.Marker({
position: location,
map: map
});
}
}
}
The function init_maps() is called when the user clicks on a link. The problem is that nothing is displayed in the div when the page loads, if I remove:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo, { timeout: 20000 });
} else {
noGeoInfo();
}
function geoInfo(position) {
the map then loads as expected. Why is it not being displayed if I have the if else to determine if geo-location is enabled?

adding a marker to your current position on google maps

Does any of you know how to add a marker on you currentPosition in google maps using sencha?
This is my code:
var map;
var defaultLocation;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var spots;
var infowindow = new google.maps.InfoWindow();
owt.views.RoutePanel = Ext.extend(Ext.Panel, {
title: 'route',
fullscreen:true,
layout: 'card',
items: [
map = new Ext.Map({
useCurrentLocation: true,
mapOptions: {zoom:10},
listeners: {
delay: 500,
afterrender: function() {
var geo = new Ext.util.GeoLocation({
accuracy: 1,
autoUpdate: true,
listeners: {
locationupdate: function (geo) {
center = new google.maps.LatLng(geo.latitude, geo.longitude);
zoom = 10;
if (map.rendered){
map.update(center)
}
else{
map.on('activate', map.onUpdate, map, {single: true, data: center});}
},
locationerror: function (geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {
if (bTimeout) {
alert('Timeout occurred.');
}
else {
alert('Error occurred.');
}
}
}
});
geo.updateLocation();
spots = [];
for (var i in owt.stores.spotStore.data.map) {
spots.push(new google.maps.LatLng(owt.stores.spotStore.data.map[i].data.lat,
owt.stores.spotStore.data.map[i].data.lng))
switch (owt.stores.spotStore.data.map[i].data.categorie_id) {
case 1:
var image = 'assets/images/monumenten_icon.png';
break;
case 2:
var image = 'assets/images/horeca_icon.png';
break;
case 3:
var image = 'assets/images/toilet_icon.png';
break;
case 4:
var image = 'assets/images/shopping_icon.png';
break;
}
var markers = [];
var spotMarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(owt.stores.spotStore.data.map[i].data.lat,owt.stores.spotStore.data.map[i].data.lng),
map: this.map,
icon: image
});
google.maps.event.addListener(spotMarker, 'dblclick', (function(spotMarker, i) {
return function() {
var win1 = new Ext.Panel({
floating:true,
layout: "card",
centered:false,
scroll: 'vertical',
styleHtmlContent: true,
centered: true,
width:280,
height:140,
html:'<img src="assets/images/spots/' + owt.stores.spotStore.data.map[i].data.naam.replace(/\s/g, "") + '.jpg"<div class="floatpanel"></div><h3>' + owt.stores.spotStore.data.map[i].data.naam + '</h3><p>' + owt.stores.spotStore.data.map[i].data.omschrijving + '</p></div>'
}).show()
}
})(spotMarker, i));
}
for (var i in owt.stores.groepStore.data.map) {
var groepMarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(owt.stores.groepStore.data.map[i].data.latitude,owt.stores.groepStore.data.map[i].data.longitude),
map: this.map,
icon: 'assets/images/groepen_icon.png'
});
(groepMarker, i);
}
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
directionsDisplay.setMap(this.map);
calcRoute();
}
}
}
)]
});
function calcRoute() {
var waypts = [];
for (var i = 1; i < 9; i++) {
waypts.push({
location:new google.maps.LatLng(owt.stores.spotStore.data.map[i].data.lat, owt.stores.spotStore.data.map[i].data.lng),
stopover:true});
}
start = new google.maps.LatLng(50.80520247265613, 3.274827003479004);
end = new google.maps.LatLng(50.8252946155155, 3.2799339294433594);
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
};
Ext.reg('owt-loginpanel', owt.views.RoutePanel);
I have tried a dozen different things but i just cant get the marker to show.
I tried running your code on Google Chrome. It seems like the locationupdate event gets called only the first time after I grant the browser the permission to access my current location. After refreshing the page, the locationupdate event did not get called anymore since I had already given the browser permission to access my current location.
You could try first setting up your GeoLocation object and use it to save the user's coordinates in a variable. I believe, you don't have to use it inside the Map's afterrender function. You could try outputting your center variable with console.log() to see if you're getting the user's location correctly.
After you have the location, it shouldn't be hard to put a marker on it.

Categories

Resources