Google Maps Marker Listeners - javascript

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.

Related

Route map are drawn improperly in google maps in javascript

I am developing a web application and integrated google maps with java script. markers are working fine with good latitude and longitude. the route map is not shown perfectly. when search users in a route map, not showing properly. it shows different routes. it didn't clear previous route. How can I clear previous route?
Route Map Screen shot
sample maps code:
var marker= [];
var geocoder;
var map;
var directionsDisplay,directionsService;
directionsDisplay = new google.maps.DirectionsRenderer({ draggable: false, suppressMarkers: true });
directionsService = new google.maps.DirectionsService();
var request = {
travelMode: google.maps.TravelMode.DRIVING
};
googleMapCoordinates(response);
function googleMapCoordinates(response) {
setMapOnAll(null);
marker = [];
directionsDisplay.setMap(null);
directionsDisplay.setPanel(null);
$("#map").show();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(17.7254567, 83.3097112),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
var i;
for (i = 0; i < response.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(response[i].latitude, response[i].longitude),
map:map,
label:response[i].count
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("Name :"+response[i].name);
infowindow.open(map, marker);
}
})(marker, i));
/******************Direction*********************************/
if (i == 0) request.origin = marker.getPosition();
else if (i == response.length - 1) request.destination = marker.getPosition();
else {
if (!request.waypoints) request.waypoints = [];
request.waypoints.push({
location: marker.getPosition(),
stopover: true
});
}
}
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
function setMapOnAll(map) {
console.log("Set map is to empty state ");
for (var i = 0; i < marker.length; i++) {
marker[i].setMap(map);
}
}

Using geoPosition.js with colobox

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;
}
}

Meteor: Uncaught ReferenceError: calcRoute is not defined

I am new to Meteor and Javascript. I am creating a map that gives directions from your current location to a marker on the map. Everything seems to work except that I can't seem to call the calcRoute() function correctly. Or maybe it is defined in the wrong place.
I think I need some schooling on template helpers. Please tell me where I went wrong. Thanks.
var gmaps = {
// map object
map: null,
//direction services object
directionsService: null,
//direction services object
directionsDisplay: null,
//direction services object
stepDisplay: null,
markerArray: []
}
Template.map.helpers({
mapOptions: function() {
if (GoogleMaps.loaded()) {
if (!Geolocation.error()) {
pos = Geolocation.latLng();
}
return {
//center: new google.maps.LatLng(-25.2743, 133.7751),
center: new google.maps.LatLng(pos.lat, pos.lng),
zoom: 12,
scaleControl: false,
zoomControl: false,
mapTypeControl: false,
panControl: false,
rotateControl: true,
overviewMapControl: false,
streetViewControl: false,
};
}
},
calcRoute: function() {
//clear markers before calculating function
gmaps.clearMarkers();
console.log(this.markerArray);
// Retrieve the start and end locations and create
// a DirectionsRequest using BICYCLING directions.
var start = marker3.getPosition();
var end = document.getElementById('marketName').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.BICYCLING
};
// Route the directions and pass the response to a
// function to create markers for each step.
this.directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
this.directionsDisplay.setDirections(response);
gmaps.showSteps(response);
}
});
},
showSteps: function(directionResult) {
// For each step, place a marker, and add the text to the marker's
// info window. 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 = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map.instance
});
gmaps.attachInstructionText(marker, myRoute.steps[i].instructions);
this.markerArray[i] = marker;
}
},
attachInstructionText: function(marker, text) {
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'mouseover', function() {
// Open an info window when the marker is clicked on,
// containing the text of the step.
stepDisplay.setContent(text);
stepDisplay.open(map.instance, marker);
})
google.maps.event.addListener(marker, 'click', function() {
map.instance.setZoom(14);
map.instance.setCenter(marker.getPosition());
stepDisplay.open(map.instance, marker);
})
},
clearMarkers: function() {
// First, remove any existing markers from the map.
for (var i = 0; i < this.markerArray.length; i++) {
this.markerArray[i].setMap(null);
}
// Now, clear the array itself.
this.markerArray = [];
}
});
Template.map.onCreated(function() {
GoogleMaps.ready('map', function(map) {
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map.instance);
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(29.71739, -95.40183),
map: map.instance,
title: 'Rice U Farmers Market'
});
var infowindow1 = new google.maps.InfoWindow({
content: ''
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.setContent( '<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(calcRoute());">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
});
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(29.81063, -95.37999),
map: map.instance,
title: 'Canino\'s Produce'
});
var infowindow2 = new google.maps.InfoWindow({
content: 'Canino\'s Produce'
});
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map.instance, marker2);
});
var image = '/img/app/flag1.png'
var marker3 = new google.maps.Marker({
position: new google.maps.LatLng(pos.lat, pos.lng),
map: map.instance,
title: 'You are here',
icon: image
});
var rendererOptions = {
map: map.instance
}
this.directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// global flag saying we intialized already
Session.set('map', true);
})
});
You have to pass the name of the method that Meteor will call as a string;
Replace:
'<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(calcRoute());">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);
with:
'<p>Farmers Market at Rice U </p>' +'<button onclick="Meteor.call(\'calcRoute\');">Directions from my Location</button>');
infowindow1.open(map.instance, marker1);

removing last added marker from google maps v3

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.

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