Connecting Direction Service in Angular - javascript

I've set up a map using AngularJS. The marker data is from a json file and is in working order. But I'd like the user to be able to click on a button (either from the item list or in the info window) to get directions from their current location to their selected destination.
I do not know how to connect Google Maps Direction Service to what I have. The current function is connected to the button in the marker list, not the info window. But I would like the direction service to work in either.
Any and all help is much appreciated. Thanks!
Here is the site (all source code is available) http://portlandstreetcarbars.com/streetcar-bars-map/app/#/
Here is the HTML:
<h3>Click on a bar below to view its location or get directions.</h3>
<div class="horizontal">
<div class="table">
<article class="list-group-item" id="class" ng-repeat="marker in markers | orderBy : 'title'">
<a href="#" ng-click="openInfoWindow($event, marker)">
<div class="img-wrap">
<img id="bar-image" class="bar-image" src={{marker.image}} />
<!-- End Image Gallery -->
</div>
<h3 class="box-title">{{marker.title}}</h3>
</a>
<input type='button' ng-click='getDirections(marker)' value='Get directions'>
</article>
</div>
</div>
<h3 class="map">Click on a marker below to view its location or get directions.</h3>
<section class="map-container">
<div id="map"></div>
<h3>Directions Go here</h3>
<div id="panel">
<input type='button' id="reset-map" ng-click='clearMarkers()' value='Reset Map'>
</div>
</section>
Here is the script:
var mapApp = angular.module('mapControllers', []);
mapApp.controller('ListController', function ($scope, $http) {
$http.get('scripts/bars.json').
success(function(data, status, headers, config) {
$scope.bars = data;
var myLatlng100 = new google.maps.LatLng(45.522535,-122.659492);
var mapOptions = {
center: myLatlng100,
zoom: 15,
mapTypeControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
};
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (bar){
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(bar.lat, bar.lng),
title: bar.name
});
marker.content = '<div class="contentString"><img src="' +
bar.image +
'"><br/>'+
bar.address +
' '+
bar.city +
', '+
bar.state +
'<button ng-click="getDirections('+bar.lat+', '+bar.lng+')">Get Directions</button>' +
'</div>';
marker.image = bar.image;
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('' +'<h2 class="info-window">' + bar.name + '</h2>' + '' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
var i;
for (i = 0; i < $scope.bars.length; i++){
createMarker($scope.bars[i]);
}
$scope.openInfoWindow = function(e, selectedMarker){
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
};
$scope.getDirections= function(marker) {
$scope.marker = marker;
$scope.lat = $scope.marker.position.D;
$scope.lng = $scope.marker.position.k;
console.log($scope.lat);
if (navigator.geolocation) { //Checks if browser supports geolocation
navigator.geolocation.getCurrentPosition(function (position) { //This gets the
var latitude = position.coords.latitude; //users current
var longitude = position.coords.longitude; //location
var start = new google.maps.LatLng(latitude, longitude); //Creates variable for map coordinates
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap($scope.map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: start,
destination: new google.maps.LatLng( $scope.lat, $scope.lng),
travelMode: google.maps.DirectionsTravelMode.TRANSIT
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
} else {
//Browser doesn't support Geolocation
handleNoGeolocation(false);
}
};
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: $scope.map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
}).
error(function(data, status, headers, config) {
console.log("Did not compute");
});
})

I fixed this issue. I had my getDir function incorrectly inside the controller (apparently).
I removed it, added map as a parameter and it works. But the direction path doesn't render on the map. So if anyone has any ideas as to how to fix this...

Related

The followind code is for geo location but it is showing over_query_limit error

I am trying to locate the user and tell him nearest doctors to him but the code is showing over_query_limit. I am not able to resolve the problem as I am new to using API's
I have tried using this code but it is again showing the same problem
{% include 'includes/default.html' %}
<head>
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAVZIr_BmEFJTyl7MzSpBS_XpLrBgZEBZg&libraries=places&sensor=false"></script>
<script src="js/script.js"></script>
<!-- <script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script> -->
<!-- <script src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyAVZIr_BmEFJTyl7MzSpBS_XpLrBgZEBZg&callback=initalize" -->
async defer></script>
<script type="text/javascript">
var geocoder;
var map;
var markers = Array();
var infos = Array();
function initialize() {
// prepare Geocoder
geocoder = new google.maps.Geocoder();
// set initial position (Byculla)
var myLatlng = new google.maps.LatLng(14.4426,78.9865);
var myOptions = { // default map options
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('gmap_canvas'),
myOptions);
}
// clear overlays function
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
infos = [];
}
}
// clear infos function
function clearInfos() {
if (infos) {
for (i in infos) {
if (infos[i].getMap()) {
infos[i].close();
}
}
}
}
// find address function
function findAddress() {
var address = '{{location}}';
// script uses our 'geocoder' in order to find location by address name
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) { // and, if everything
is ok
// we will center map
var addrLocation = results[0].geometry.location;
map.setCenter(addrLocation);
// store current coordinates into hidden variables
document.getElementById('lat').value =
results[0].geometry.location.lat();
document.getElementById('lng').value =
results[0].geometry.location.lng();
// and then - add new custom marker
var addrMarker = new google.maps.Marker({
position: addrLocation,
map: map,
title: results[0].formatted_address,
icon: 'marker.png'
});
} else {
alert('Geocode was not successful for the following reason: ' +
status);
}
findPlaces();
});
}
// find custom places function
function findPlaces() {
// prepare variables (filter)
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
var cur_location = new google.maps.LatLng(lat, lng);
// prepare request to Places
var request = {
location: cur_location,
radius: 2000,
types: ['hospital','doctor']
};
// send request
service = new google.maps.places.PlacesService(map);
service.search(request, createMarkers);
}
// create markers (from 'findPlaces' function)
function createMarkers(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// if we have found something - clear map (overlays)
clearOverlays();
// and create new markers by search result
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
} else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS)
{
alert('Sorry, nothing is found');
}
}
// creare single marker function
function createMarker(obj) {
// prepare new Marker object
var mark = new google.maps.Marker({
position: obj.geometry.location,
map: map,
title: obj.name
});
markers.push(mark);
// prepare info window
var infowindow = new google.maps.InfoWindow({
content: '<img src="' + obj.icon + '" /><font style="color:#000;">' +
obj.name +
'<br />Rating: ' + obj.rating + '<br />Vicinity: ' + obj.vicinity + '
</font>'
});
// add event handler to current marker
google.maps.event.addListener(mark, 'click', function() {
clearInfos();
infowindow.open(map,mark);
});
infos.push(infowindow);
}
// initialization
google.maps.event.addDomListener(window, 'load', initialize);
document.getElementById("doctortab").click();
</script>
</head>
<body onload="findAddress()">
<div id="gmap_canvas" style="position: absolute; top:200px;right:20px
;height:400px;width:800px">
</div>
<input type="hidden" id="lat" name="lat" value="18.9682846" />
<input type="hidden" id="lng" name="lng" value="72.8311396" />
<!-- <input type="hidden" value="{{location}}" id="location"
name='location'> -->
</body>
The expected result is to show the user doctor but it is showing over_query_limit error
If you use Google's geolocation system, last time they made more limits to the free users. You just had to pay for higher connection limits or something like that. Anyway, you didnt posted your code.

Google Maps API Directions Service Displaying Text Directions Repeating

I'm using the Google Maps JavaScript API to display routes and text directions:
JS:
var geocoder;
var map;
var search_lat;
var search_lng;
function initMap() {
var myLatLng = {
lat: 38.5803844,
lng: -121.50024189999999
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: myLatLng,
});
geocoder = new google.maps.Geocoder();
document.getElementById('search_button').addEventListener('click', function() {
getDirectionsByAddress(geocoder, map);
});
var locations = <?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][5], locations[i][6]),
animation: google.maps.Animation.DROP,
icon: icon_image,
map: map
});
}
}
function getDirectionsByAddress() {
// GET THE SEARCH ADDRESS
var address = document.getElementById('address').value;
console.log('search address: ' + address);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
search_lat = results[0].geometry.location.lat();
search_lng = results[0].geometry.location.lng();
console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
// INITIALIZE GOOGLE MAPS DIRECTIONS SERVICE
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
calculateAndDisplayRoute(directionsService, directionsDisplay);
// CHECK THE MODE OF TRAVEL
document.getElementById('mode').addEventListener('change', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
// CALCULATE THE DIRECTIONS BASED ON ADDRESS ENTERED AND MODE OF TRAVEL
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: {lat: search_lat, lng: search_lng},
destination: {lat: 38.5803844, lng: -121.50024189999999},
travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
I'm having trouble with the getDirectionsByAddress function. When I search a location and click the "search button" the first time, nothing happens. On the second click of the "search button", the route is drawn successfully on the map and the directions are displayed, however the directions are displayed twice (it seems the directions were calculated on the first click, but only on the second click are they being displayed). If I search a third time, the third set of directions are tacked on and this repeats over and over.
It seems I need to reset the lat and lng values during each search. I tried:
delete search_lat;
delete search_lng;
inside and at the end of the calculateAndDisplayRoute function. No luck.
HTML:
<div id="map"></div>
<div id="directions">
<h3>Directions</h3>
</div>
<div class="search_block">
<input type="text" name="address" id="address" class="address" placeholder="Where are you coming from?" />
</div>
<div class="search_block">
<select name="travel_mode" id="mode">
<option>DRIVING</option>
<option>WALKING</option>
<option>BICYCLE</option>
<option>TRANSIT</option>
</select>
</div>
<div class="search_block">
<button id="search_button" onclick="getDirectionsByAddress();">Search</button>
</div>
Question: How can I make it so the directions are refreshed with a single set of coordinates during each search?
search_lat and search_lng are null until the geocoder returns results.
the geocoder is asynchronous, its results don't come back until after you place the first call to the directions service.
a hint is this error in the javascript console: Uncaught TypeError: Cannot read property 'b' of null
Move the call to the directions service into the callback function for the geocoder (where/when the data exists).
Fix that, and create a single instance of the DirectionsRenderer and it works for me.
proof of concept fiddle
code snippet:
google.maps.event.addDomListener(window, "load", initMap);
var geocoder;
var map;
var search_lat;
var search_lng;
var directionsDisplay;
var directionsService;
function initMap() {
var myLatLng = {
lat: 38.5803844,
lng: -121.50024189999999
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: myLatLng,
});
directionsDisplay = new google.maps.DirectionsRenderer;
directionsService = new google.maps.DirectionsService;
geocoder = new google.maps.Geocoder();
document.getElementById('search_button').addEventListener('click', function() {
getDirectionsByAddress(geocoder, map);
});
var locations = []; //<?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][5], locations[i][6]),
animation: google.maps.Animation.DROP,
icon: icon_image,
map: map
});
}
}
function getDirectionsByAddress() {
// GET THE SEARCH ADDRESS
var address = document.getElementById('address').value;
console.log('search address: ' + address);
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
search_lat = results[0].geometry.location.lat();
search_lng = results[0].geometry.location.lng();
console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
calculateAndDisplayRoute(directionsService, directionsDisplay);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
// INITIALIZE GOOGLE MAPS DIRECTIONS SERVICE
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
// CHECK THE MODE OF TRAVEL
document.getElementById('mode').addEventListener('change', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
// CALCULATE THE DIRECTIONS BASED ON ADDRESS ENTERED AND MODE OF TRAVEL
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: {
lat: search_lat,
lng: search_lng
},
destination: {
lat: 38.5803844,
lng: -121.50024189999999
},
travelMode: google.maps.TravelMode[selectedMode]
}, 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: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="directions">
<h3>Directions</h3>
</div>
<div class="search_block">
<input type="text" name="address" id="address" class="address" placeholder="Where are you coming from?" value="San Franscisco, CA" />
</div>
<div class="search_block">
<select name="travel_mode" id="mode">
<option>DRIVING</option>
<option>WALKING</option>
<option>BICYCLE</option>
<option>TRANSIT</option>
</select>
</div>
<div class="search_block">
<button id="search_button" onclick="getDirectionsByAddress();">Search</button>
</div>
<div id="map"></div>

Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api

doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
script(src='/javascripts/jquery.min.js')
script(src='http://maps.google.com/maps/api/js?key=AIzaSyD6MCxtDJOnbE1T6Y09k8Uca1rXHTQ3Bqg&v=3.exp&sensor=true&libraries=place‌​s')
script(src='/javascripts/global.js')
h1= title
#loading
p Loading your location
br
#map
input#my-address(type='text')
button#getCords(onclick='codeAddress();') getLat&Long
I write above code in jade template for display the map i.e 'index.jade' and
following file i.e 'global.js' is script file
//Calling the locateme function when the document finishes loading
$(document).ready(function() {
locateMe();
});
//Function to locate the user
var locateMe = function(){
var map_element= $('#map');
if (navigator.geolocation) {
var position= navigator.geolocation.getCurrentPosition(loadMap);
} else {
map_element.innerHTML = "Geolocation is not supported by this browser.";
}
};
//Lets load the mop using the position
var loadMap = function(position) {
var loading= $('#loading');
var latitude=position.coords.latitude;
var longitude=position.coords.longitude;
var myLatlng = new google.maps.LatLng(latitude, longitude);
//Initializing the options for the map
var myOptions = {
center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
//Creating the map in teh DOM
var map_element=document.getElementById("map");
var map = new google.maps.Map(map_element,myOptions);
//Adding markers to it
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'You are here'
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow({
content: "<h2>You are here:</h2>",
//Settingup the maxwidth
maxWidth: 300
});
//Event listener to trigger the marker content
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);});
};
//get lat and log
function codeAddress() {
alert('inside')
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var map = new google.maps.Map(document.getElementById("my-address"),{
center:pyrmont,
zoom:15
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow();
alert(infowindow);
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
};
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api
You are doing Place Search which doesnt return all of the fields that you are using:
http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_responses
In order to get the address, website, etc, you'll also need to call place.getDetails(), passing the Place's reference.
Below is a sample code snippet how to get Places details:
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
infowindow.open(map, this);
});
});
}

google maps event.addListener with xml

I am working on a dealerlocator with google maps. The problem is that when I click on a icon the infowindow opens the wrong window. I use a xml import. Everything is going well until the infowindow.
see website https://www.turbho.com/dealerview.php
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2maN7CjzWtwI6yuHj8lX078NzV0Ywkg0&sensor=false"></script>
{literal}
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// 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,
panControl: true,
zoomControl: true,
scaleControl: true,
content: 'U bent nu hier.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesnt support Geolocation
handleNoGeolocation(false);
}
var image = 'https://turbho.com/img/logoturbhogooglesmall.png';
// Change this depending on the name of your PHP file
downloadUrl("xml/datacomplete.xml", function (data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var zipcode = markers[i].getAttribute("zipcode");
var town = markers[i].getAttribute("town");
var anchor = markers[i].getAttribute("anchor");
var website = markers[i].getAttribute("website");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<span style='font-size:12px;'><b>" +
name + "</b> <br />" +
address + "<br />" +
zipcode + " " + town + "<br /><br />" +
website + "<br /><br />" +
anchor + "</span>";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image
});
var infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function () {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
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);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
{/literal}
<div id="map-canvas"></div>
The problem is solved. I used a function see below and that worked for me.
function add_marker(latlng, title, box_html, image) {
//create the global instance of infoWindow
if (!window.infowindow) {
window.infowindow = new google.maps.InfoWindow();
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: title,
icon: image
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.close();
infowindow.setContent(box_html);
infowindow.open(map, this)
});
return marker;
}
Thanx for the help
Ruud

Trying to call a function with an existing eventListener

My knowledge of javascript isnt great, so im not sure exactly how to load this second function from the same event listener.
var tutsImg = "houseProxy.jpg";
var kingTuts = new google.maps.LatLng(55.86256, -4.265);
var tutsDisplay = new google.maps.Marker({
position: kingTuts,
map: map,
icon: tutsImg,
title:"King Tut's Wah Wah Hut"
});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h2 id="firstHeading" class="firstHeading">King Tuts Wah Wah Hut</h2>'+
'<div id="bodyContent">'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
// Creating directions
function calcRoute () {
var request = {
origin: 'Glasgow',
destination: kingTuts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addListener(tutsDisplay, 'click', function() {
infowindow.open(map,tutsDisplay);
calcRoute();
});
So here i create the variables to display a custom marker on the location of my chosen building. But i also want to call the function which calculates and displays the directions from the users current location to the location of the clicked icon.
any help guys?
I can not fully understand what is the problem.
But I write code which will be show direction from user location
to the location of clicked on map. For getting user location I using geolocation API (HTML5).
I hope this helps you :)
(function(global) {
var google = global.google;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay;
// initialize google map
var initialize = function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// initialize map
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
// add event on map click
// #param {Object} event The custom map event object
// which contain latitude and langitude
google.maps.event.addListener(map, 'click', function(event) {
// getUserPosition is async function
// because it require user permission
getUserPosition(calcRoute.bind(global, event.latLng));
});
};
// html 5 geolocation API
// Get user position
var getUserPosition = function(callback) {
global.navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var langitude = position.coords.longitude;
// convert user position to google.maps
// LatLng object
var origin = new google.maps.LatLng(latitude, langitude);
callback(origin);
} /*, onError */ );
};
// calc direction from user location
// to position clicked on map
var calcRoute = function(distPosition, originPosition) {
var request = {
origin: originPosition,
destination: distPosition,
travelMode: google.maps.TravelMode.DRIVING // it's work onliy for one continent
};
directionsService.route(request, function(result, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
};
// events
google.maps.event.addDomListener(window, 'load', initialize);
}(this));
Link on gist

Categories

Resources