Web Worker threads for Google Maps - javascript

I am trying to use web worker threads to grab directions between multiple pairs of locations parallelly and store the text in a file in the end. Everything had gone well in the sequential approach. I am using npm live-server to display the page. But the browser just closes the page instantly after it loads and I don't even get to see what rendered or consult the console for errors. If I use 'async defer' for my script tag with the google Api in index.html, I would get the "UncaughtReferenceError: google is not defined" error. Thanks in advance guys!
Here is my index.html:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
#map {
height: 100%;
width: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
panel {
display: block;
}
</style>
</head>
<body>
<panel></panel>
<div id="map"></div>
<script src=locations.js></script>
<script src='main.js'></script>
<script src='worker.js'></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<API-KEY>&callback=initMap"></script>
</body>
</html>
Here is my main.js:
let worker = new Worker('worker.js');
worker.onmessage = function(info) {
output += info.data;
};
const container = document.querySelector('panel');
let output = ""
function initMap() {
locations.forEach( spot => {
worker.postMessage(spot);
});
download("data.txt", output, 'text/plain');
console.log("Output: " + output);
}
function download(name, text, type) {
const file = new Blob([text], {type: type});
const atag = 'Download';
container.insertAdjacentHTML('afterbegin', atag);
}
And, finally the worker.js:
let directionsService;
let directionsDisplay;
let map;
self.addEventListener('message', (e) => {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
const mapOptions = {
center: {lat: 30, lng: -90},
zoom: 6
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
let request = {
origin: 'New Orleans, LA',
destination: e.data,
travelMode: 'DRIVING',
provideRouteAlternatives: false,
drivingOptions: {
departureTime: new Date('September 7, 2018 15:00:00'),
trafficModel: 'pessimistic'
},
unitSystem: google.maps.UnitSystem.IMPERIAL
};
directionsService.route(request, (result, status) => {
if (status == 'OVER_QUERY_LIMIT') {
console.log('over');
}
if (status == 'INVALID_REQUEST'){
console.log('other status')
}
if (status == 'OK') {
var data = result["routes"][0].legs[0];
postmessage(e.data + ", " + data["distance"].text + ", " + data["duration"].text + "\n");
directionsDisplay.setDirections(result);
console.log(result);
}
});
self.close();
});

Web workers have their own scope in Javascript. This means any scripts you loaded in the scope of the web page will not be available in the scope of the web worker.
Usually you use the importScripts call to load a script. However this won't work in your case because you also try to access the DOM in the web worker. This is not possible in a web worker for a number of reason (most important would be concurrent access to a data structure which is not thread save).
Looking at your code I don't think you need a web worker to calculate the routes. Most likely the actual routing is done on one of Googles servers anyway. Since this would be async anyway you do not need to worry about blocking the UI of your web page.

Related

google map api markers with realtime data

I currently have realtime analytics php api. It has this entity named $resulting. If I do print_r($resulting); it returns for example (if only 1 user is online):
Array ( [0] => Array ( [0] => Arnhem [1] => 5.898730 [2] => 51.985104 [3] => Chrome [4] => DESKTOP [5] => / [6] => 1 ) )
Now, later on in the same file, I have the google maps javascript api.
It has markers in the form of:
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
As placeholder for now.
What I want to do, is have in the coords: section have the lat: and lng: be the appropriate values from $resulting.
Also, I want to have as many markers as there are users online.
Now, I have tried everything I can think of, but I can't get it to work.
I have tried for example:
const results = <? php echo json_encode($resulting); ?>;
let markers = [];
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
}
};
}
but then the maps won't load anymore.
I have tried looping, foreach, trying to get the lat: and lng: to update with the values returned by $resulting, but whatever I do it simply won't work.
Can anybody help me and get this working?
Thanks.
edit:
adding the index.php file as requested:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php
require_once __DIR__ . '/../google/vendor/autoload.php';
$analytics = initializeAnalytics();
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . 'MY KEY FILE LOCATION';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
}
/**
* 1.Create and Execute a Real Time Report
* An application can request real-time data by calling the get method on the Analytics service object.
* The method requires an ids parameter which specifies from which view (profile) to retrieve data.
* For example, the following code requests real-time data for view (profile) ID 56789.
*/
$optParams = array(
'dimensions' => 'rt:city, rt:longitude, rt:latitude, rt:browser, rt:deviceCategory, rt:pagePath');
try {
$resultsrealtime = $analytics->data_realtime->get(
'ga:MY GOOGLE CLIENT ID',
'rt:activeUsers',
$optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
/**
* 2. Print out the Real-Time Data
* The components of the report can be printed out as follows:
*/
$resulting = $resultsrealtime->getRows();
function test() {
if(count($resulting == false)){
return;
}
else if(count($resulting) > 0){
foreach ($resulting as $resultingTwo => $resultingThree) {
foreach ($resultingThree as $resultingFour){
echo $resultingFour.'<br />';
}
}
} else {
echo 'No visitors';
}
}
?>
<script>
// Map options
function initMap(){
var options = {
zoom:7,
center:{lat:52.0907, lng:5.1214}
}
// New map
var map = new google.maps.Map(document.getElementById('map'), options);
// Array of markers
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
iconImage:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
// Loop through markers
for(var i = 0; i < markers.length; i++){
// add Marker
addMarker(markers[i]);
}
// Add Marker Function
function addMarker(props){
var marker = new google.maps.Marker({
position: props.coords,
map:map,
//icon:props.iconImage
});
// Check for custom icon
if(props.iconImage){
// Set icon image
marker.setIcon(props.iconImage);
}
// Check for content
if(props.content){
// Set content
// Info Window
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('mouseover', function(){
infoWindow.open(map, marker);
// Reset Info Window
setTimeout(function(){
infoWindow.open()
}, 500);
}, false);
}
}
}
</script>
<div id="data"><p><?php $test = json_encode($resulting); print_r($test);?></p></div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Also, what the json_encode returns with 2 users online:
[["Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"],["Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1"]]
You should also assign the map object to the marker (assuming your map object is named map )
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
},
map: map
};
}
To help you identify the issue, it would be useful to see the rest of your javascript code for the map api, as well as the array when there's more than one user after running it though json_encode(). That said, try the following:
const results = <? php echo json_encode($resulting); ?>;
for(let i = 0; i < results.length; i++) {
let marker = new google.maps.Marker({
position: {lat: results[1], lng: results[2]},
content: '<h1>' + results[0] + </h1>,
map: map
});
}
Edit:
I don't have Composer installed in the directory I tested your code in, and I haven't worked much with the Google realtime API, but the following javascript will work given the output you listed for $resulting. You'll have to tweak things depending on where your custom icons are coming from, but that should be pretty straightforward.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php $resulting = array(array("Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"), array("Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1")); ?>
<script>
const resultingArr = <?php echo json_encode($resulting); ?>;
function initMap() {
var options = {
zoom: 7,
center: {
lat: 52.0907,
lng: 5.1214
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
function mapMarkers(props) {
const marker = new google.maps.Marker({
position: props.coords,
map: map,
icon: props.iconImage
});
const infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.addListener('mouseover', function() {
infoWindow.open(map, marker);
});
marker.addListener('mouseout', function() {
infoWindow.close();
});
}
for (let i = 0; i < resultingArr.length; i++) {
mapMarkers({
coords: {
lat: parseFloat(resultingArr[i][2]),
lng: parseFloat(resultingArr[i][1])
},
content: '<h3>' + resultingArr[i][0] + '</h3>'
})
}
};
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Hope this helps!

How to have my bing maps accept real time lat and long coordinates and track my athlete live along the map

I have just added bing maps and API to my in development site however I am needing some help understanding how to have my code accept live updating lat and long coordinates and have my map update the marker in regards to these values.
Currently this is what I have but part of the code was designed for google maps which I replaced the words google with Microsoft hoping for the best.
Please be gentle I am new to coding
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=release&callback=loadMapScenario' async defer></script>
</head>
<body>
<div id='printoutPanel'></div>
<div id='myMap' style='width: 400px; height: 400px;'></div>
<script type='text/javascript'>
// Setting boundary and loading map
function loadMapScenario() {
var bounds = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(29.332823, -81.492279), new Microsoft.Maps.Location(28.435825, -81.622231));
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'Bing Maps Key',
maxBounds: bounds
});
// Highlighting the border of bounds on the map
var boundsBorder = new Microsoft.Maps.Polyline([bounds.getNorthwest(),
new Microsoft.Maps.Location(bounds.getNorthwest().latitude, bounds.getSoutheast().longitude),
bounds.getSoutheast(),
new Microsoft.Maps.Location(bounds.getSoutheast().latitude, bounds.getNorthwest().longitude),
bounds.getNorthwest()], { strokeColor: 'red', strokeThickness: 2 });
map.entities.push(boundsBorder);
}
</script>
<script>
function getReverseGeocodingData(lat, lng) {
var latlng = new Microsoft.maps.LatLng(lat, lng);
// This is making the Geocode request
var geocoder = new Microsoft.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== Microsoft.maps.GeocoderStatus.OK) {
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == Microsoft.maps.GeocoderStatus.OK) {
console.log(results);
var address = (results[0].formatted_address);
}
});
}
</script>
The Bing Maps V8 team actually has a documented code sample on how to do exactly this here: https://msdn.microsoft.com/en-us/library/mt712803.aspx

Display step by step Google map Direction

sorry for my bad english.
i looking for a solution to trace a route on a google map, display progressively street names when user move and read by TTS google map instructions.. (like a GPS)
I wish to display the following instruction when the user approaches the previous instruction
My watchPosition function call geolocationSuccess function each movement, this is not a good solution
In my example i trace a route from my geolocation to Omaha beach museum Normandy France
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Geolocation and Google Maps API</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function geolocationSuccess(position) {
var destination="49.366973,-0.882042";
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
direction = new google.maps.DirectionsRenderer({
map : mapObject,
suppressMarkers : true
// panel : panel // Dom element pour afficher les instructions d'itinéraire
});
if(userLatLng && destination){
var request = {
origin : userLatLng,
destination : destination,
travelMode : google.maps.DirectionsTravelMode.DRIVING // Mode de conduite
}
var directionsService = new google.maps.DirectionsService(); // Service de calcul d'itinéraire
directionsService.route(request, function(response, status){ // Envoie de la requête pour calculer le parcours
if(status == google.maps.DirectionsStatus.OK){
direction.setDirections(response); // Trace l'itinéraire sur la carte et les différentes étapes du parcours
}
var myRoute = response.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
console.log(myRoute.steps[i].instructions+' -> '+myRoute.steps[i].distance.value);
}
console.log(myRoute.steps[0].instructions)
$("#route").html('Dans '+myRoute.steps[0].distance.value+' m '+myRoute.steps[0].instructions);
readbyTTS(myRoute.steps[0].instructions);
var follow = navigator.geolocation.watchPosition(function(position) {
geolocationSuccess(position);
});
});
}
}
function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br />";
}
function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation)
{
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
<style type="text/css">
#map {
width: 800px;
height: 600px;
}
</style>
</head>
<body>
<h1></h1>
<div id="map"></div>
<p><span id="route"></span></p>
<p id="error"></p>
</body>
</html>
Thanks for your help
KilRoy
You can try to use Google Maps Directions API, it is a service that calculates directions between locations using an HTTP request.
This service is generally designed for calculating directions for static (known in advance) addresses for placement of application content on a map; this service is not designed to respond in real time to user input.
Check this SO question for more information.

Google Maps API V3 : How to get multiple path distances using direction from a point A to point B

I can get only one driving distance from point A to point B using google map api v3.
Code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Complex</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 13px; color: red;">
<div id="map" style="width: 400px; height: 300px;"></div>
<div id="duration">Duration: </div>
<div id="distance">Distance: </div>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsDisplay.setMap(map);
var st=new google.maps.LatLng(51.7519, -1.2578);
var en=new google.maps.LatLng(50.8429, -0.1313);
var request = {
origin: st,
destination:en,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the distance:
document.getElementById('distance').innerHTML +=
(response.routes[0].legs[0].distance.value)/1000 + "killo meters";
alert((response.routes[0].legs[0].distance.value)/1000 + "killo meters");
// Display the duration:
document.getElementById('duration').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
alert( response.routes[0].legs[0].duration.value + " seconds");
directionsDisplay.setDirections(response);
}
});
</script>
</body>
</html>
But I want to get multiple or all possible driving distances using google map api v3. I want to get multiple distances like given below.
There is a provideRouteAlternatives options that can be specified with the directions request parameters to tell the DirectionsService to return multiple results. You can amend your request parameters as follows:
var request = {
origin: st,
destination: en,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
// Returns multiple routes
provideRouteAlternatives: true
};
Your event handler for obtaining the directions can be modified to create a new DirectionsRenderer for each route as follows (ensure you set the correct route index each time, otherwise the DirectionsRenderer will render the first route in the response):
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Create a new DirectionsRenderer for each route
for (var i = 0; i < response.routes.length; i++) {
var dr = new google.maps.DirectionsRenderer();
dr.setDirections(response);
// Tell the DirectionsRenderer which route to display
dr.setRouteIndex(i);
dr.setMap(map);
// Code ommited to display distance and duration
}
}
}
The code where you append the distance and duration will need to be brought into this for loop so it appends the distance and duration for each route. I've ommited this in the code snippet above but it is in the demo Fiddle below.
I've created a Fiddle to demonstrate this.

google maps displaying a route

according to google maps i can plan a route that crosses over several waypoints. It is explained here:http://code.google.com/intl/nl-NL/apis/maps/documentation/javascript/services.html#Routes
Now the api wants me to add the waypoints like this:
location: waypoints
so waypoints is an array wich i have to assign to the location: parameter but from what ive seen in the demo they fill the array with strings of the locations. What i was wondering if it was possible to pass the latitude and longitude instead of the strings?
update: this is the part where i try to create a route. i have put the same value in location throughout the entire loop for now but id doesn't work if i use variable values neither
function calcRoute() {
var waypts = [];
for (var i in owt.stores.spotStore.data.map) {
waypts.push({
location: new google.maps.LatLng(12.3, -33.6),
stopover:true
});
console.log(waypts);
}
var request = {
origin: new google.maps.LatLng(50.82788, 3.26499),
destination: new google.maps.LatLng(50.82788, 3.26499),
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
;
According to the API reference:
A DirectionsWaypoint represents a location between origin and destination through which the trip should be routed.
location LatLng|string Waypoint
location. Can be an address string or
LatLng. Optional
So creating a new Waypoint with a lat-long value should be as below
return {
location:new google.maps.LatLng(12.3, -33.6),
stopover:true
};
According to google documentation the waypoint can be either a string or a LatLng object.
http://code.google.com/apis/maps/documentation/javascript/reference.html#DirectionsWaypoint
here is an example using LatLng
<!DOCTYPE html>
<html>
<head><meta name="viewport" content="initial-scale=1.0, user-scalable=no"/><meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Waypoints</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(-40.321, 175.54);
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var waypts = [];
stop = new google.maps.LatLng(-39.419, 175.57)
waypts.push({
location:stop,
stopover:true});
start = new google.maps.LatLng(-40.321, 175.54);
end = new google.maps.LatLng(-38.942, 175.76);
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];
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:70%;height:80%;">
</div>
<br />
<div>
</div>
</body>
</html>
The way points can be either a string or a latlng.
http://code.google.com/intl/nl-NL/apis/maps/documentation/javascript/services.html#Directions
In particular:
waypoints[] (optional) specifies an
array of DirectionsWaypoints.
Waypoints alter a route by routing it
through the specified location(s). A
waypoint is specified as an object
literal with fields shown below:
location specifies the location of the waypoint, either as a LatLng or as
a String which will be geocoded.
stopover is a boolean which indicates that the waypoint is a stop
on the route, which has the effect of
splitting the route into two routes.
(For more information on waypoints,
see Using Waypoints in Routes below.)
EDIT
Your way points are not valid for routing, i.e. they are in water - try centering a map on (12, -33.6).
Here's a sample using way points (not the prettiest code, but it's an example ;) ).
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
var myRouter = {
map_: null,
directionsHelper_: null,
stores: [
{name: "store1", location: new google.maps.LatLng(50.82788, 3.76499)},
{name: "store2", location: new google.maps.LatLng(51.02788, 3.9)}
],
calcRoute: function() {
var waypts = [];
for (var i in this.stores) {
waypts.push({
location: this.stores[i].location,
stopover:true
});
}
var request = {
origin: new google.maps.LatLng(50.82788, 3.26499),
destination: "Antwerp",
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
var _SELF = this;
this.directionsHelper_.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
_SELF.directionsDisplay_.setDirections(response);
return;
}
console.log('Directions Status: ' + status);
});
},
init: function(mapid) {
this.directionsHelper_ = new google.maps.DirectionsService();
this.directionsDisplay_ = new google.maps.DirectionsRenderer();
var center = new google.maps.LatLng(50.82788, 3.26499);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
this.map_ = new google.maps.Map(document.getElementById(mapid), myOptions);
this.directionsDisplay_.setMap(this.map_);
this.calcRoute();
}
};
$(document).ready(function() {
myRouter.init('map');
});
</script>
<style type="text/css">
#map {
height: 500px;
width: 600px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>

Categories

Resources