Can't get Google map to display - javascript

Working from Google-generated code, I am trying to get a Google map to display on a page for a user to enter/select an address using Google Places. The relevant HTML/CSS code is as follows:
<style>
.map {
width: 300px;
}
.card-container {
display: flex;
height: 500px;
width: 600px;
}
.panel {
background: white;
width: 300px;
padding: 20px;
display: flex;
flex-direction: column;
justify-content: space-around;
}
</style>
<div class="card-container">
<div class="panel">
<div class="map" id="gmp-map"></div>
</div>
</div>
The script code for this page is as follows:
<script>
$(document).ready(function () {
"use strict";
$('#location-input').focus();
})
function initMap() {
const CONFIGURATION = {
"ctaTitle": "Checkout",
"mapOptions": { "center": { "lat": 37.4221, "lng": -122.0841 }, "fullscreenControl": true, "mapTypeControl": false, "streetViewControl": true, "zoom": 11, "zoomControl": true, "maxZoom": 22, "mapId": "" },
"mapsApiKey": "YOUR_API_KEY",
"capabilities": { "addressAutocompleteControl": true, "mapDisplayControl": true, "ctaControl": true }
};
const componentForm = [
'location',
'street_number',
'route',
'locality',
'administrative_area_level_1',
'postal_code',
];
const getFormInputElement = (component) => document.getElementById(component + '-input');
const map = new google.maps.Map(document.getElementById("gmp-map"), {
zoom: CONFIGURATION.mapOptions.zoom,
center: { lat: 37.4221, lng: -122.0841 },
mapTypeControl: false,
fullscreenControl: CONFIGURATION.mapOptions.fullscreenControl,
zoomControl: CONFIGURATION.mapOptions.zoomControl,
streetViewControl: CONFIGURATION.mapOptions.streetViewControl
});
const marker = new google.maps.Marker({ map: map, draggable: false });
const autocompleteInput = getFormInputElement('location');
const autocomplete = new google.maps.places.Autocomplete(autocompleteInput, {
fields: ["address_components", "geometry", "name", "formatted_address"],
types: ["address"],
});
autocomplete.addListener('place_changed', function () {
marker.setVisible(false);
const place = autocomplete.getPlace();
if (!place.geometry) {
$('#addrErr').text('No details available for input: \'' + place.name + '\'')
$('#toastAddrErr').toast('show');
return;
}
$('#longAddress').val(place.formatted_address);
renderAddress(place);
fillInAddress(place);
});
function fillInAddress(place) { // optional parameter
const addressNameFormat = {
'street_number': 'short_name',
'route': 'long_name',
'locality': 'long_name',
'administrative_area_level_1': 'short_name',
'postal_code': 'short_name',
};
const getAddressComp = function (type) {
for (const component of place.address_components) {
if (component.types[0] === type) {
return component[addressNameFormat[type]];
}
}
return '';
};
getFormInputElement('location').value = getAddressComp('street_number') + ' ' + getAddressComp('route');
for (const component of componentForm) {
if (component !== 'location') {
getFormInputElement(component).value = getAddressComp(component);
}
}
}
function renderAddress(place) {
alert(place.geometry.location);
map.setCenter(place.geometry.location);
marker.setPosition(place.geometry.location);
marker.setVisible(true);
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<MY_KEY_REMOVED_FOR_QUESTION>&libraries=places&callback=initMap&solution_channel=GMP_QB_addressselection_v1_cABC"></script>
I have removed my API key, by the way.
In any event, everything works as it should, and the text boes displaying address information (not included here) properly populate from the callback, except that the map never renders when the page loads (there's a default already loaded), and it doesn't render after the user enters and selects an address.
There are no messages in the console, and when I put alerts in the renderAddress() function to see if it's even being reached, they display correct information. The map is failing silently, and I don't know why.
Any thoughts?

Related

How to get a draggable waypoint's location from google directions result

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lokacija Partnerja</title>
<!--stili za elemente na mapi-->
<style type="text/css">
html {
font-family: Arial, Helvetica, sans-serif;
font-size: 15px;
height: 100%;
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
/* start styles for the ContextMenu */
.context_menu {
background-color: white;
border: 1px solid gray;
}
.context_menu_item {
padding: 3px 6px;
}
.context_menu_item:hover {
background-color: #CCCCCC;
}
.context_menu_separator {
background-color: gray;
height: 1px;
margin: 0;
padding: 0;
}
/* end styles for the ContextMenu */
#map_container {
height: 100%;
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=quarterly&key=#YOURAPIKEY#&sensor=false"></script>
<script type="text/javascript">
function initMap() {
var map = new google.maps.Map(document.getElementById('map_container'), {
zoom: 4,
center: {
lat: -24.345,
lng: 134.46
} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute('Perth, WA', 'Sydney, NSW', directionsService,
directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
waypoints: [{
location: 'Adelaide, SA'
}, {
location: 'Broken Hill, NSW'
}],
travelMode: 'DRIVING',
avoidTolls: true
}, function(response, status) {
if (status === 'OK') {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var route = result.routes[0];
for (var ij = 0; ij < route.legs[0].via_waypoints.length; ij++) {
counter = counter + 1;
//alert(counter + ", " + route.legs[i].via_waypoints[ij].B + ", " + route.legs[i].via_waypoints[ij].k)
route.legs[0].via_waypoints[ij].k,
route.legs[0].via_waypoints[ij].D
}
}
</script>
</head>
<body onload="initMap()">
<div id="map_container"></div>
</body>
</html>
I am trying to capture the location of a draggable waypoint in a google direction javascript API, so I can save it the database and load the same directions later.
I try to acces the waypoint's location via result.routes[0].legs[0].via_waypoints[0], which offers me nothing useful - lat and lng object are "empty" instead of containing geolocation (same goes for result.routes[0].legs[0].via_waypoint[0].location.
I have a remark in my code to access waypoint's geolocation via result.routes[0].legs[0].via_waypoints[0].k and result.routes[0].legs[0].via_waypoints[0].D, which does not work. I found on stackoverflow a similar question from 2011, which suggests to use location.wa and location.ya, which also does not work.
I've added a code snippet, you should replace #YOURAPIKEY# with your Google API key for the example to work. It's a slightly modified example from Google's documentation
Can anyone help me with this?
Each leg of your route is a set of steps and in the case you submitted, each leg corresponds to directions between one of your stops (origin, waypoints, destination).
leg[0] from Perth to Adelaide
leg[1] from Adelaide to Broken Hill
leg[2] from Broken Hill to Sydney
So you won't have anything in the via_waypoints prop.
You need to set stopover: false in your waypoints if you want them not considered as a real stop. Then you will get the via_waypoints property populated for each leg (if more than one).
waypoints: [{
location: 'Adelaide, SA',
stopover: false
}, {
location: 'Broken Hill, NSW',
stopover: false
}],
You can then iterate though via_waypoints and get the coordinates.
lat and lng are methods, not properties, so you need to call them, for example:
let firstWaypointLat = result.routes[0].legs[0].via_waypoints[0].lat();
Example below on how to get the waypoints coordinates:
function initMap() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 4,
center: {
lat: -24.345,
lng: 134.46
} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute('Perth, WA', 'Sydney, NSW', directionsService,
directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
waypoints: [{
location: 'Adelaide, SA',
stopover: false
}, {
location: 'Broken Hill, NSW',
stopover: false
}],
travelMode: 'DRIVING',
avoidTolls: true
}, function(response, status) {
if (status === 'OK') {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
function computeTotalDistance(result) {
let leg = result.routes[0].legs[0];
for (let i=0; i<leg.via_waypoints.length; i++) {
console.log('Waypoint ' + i + ' coords: ' + leg.via_waypoints[i].lat() + ', ' + leg.via_waypoints[i].lng());
}
}
initMap();
#map-canvas {
height: 180px;
}
<div id="map-canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Google MyMaps to Google Maps API

I am trying to recreate the following map, made using Google MyMaps, by using Google Maps API
Anyone know the best way to do this? Have the following code at the moment but doesn't look great
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search for up to 200 places with Radar Search</title>
<style>
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
var map;
var infoWindow;
var service;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 54.607868,
lng: -5.926437
},
zoom: 10,
styles: [{
stylers: [{
visibility: 'simplified'
}]
}, {
elementType: 'labels',
stylers: [{
visibility: 'off'
}]
}]
});
infoWindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
// The idle event is a debounced event, so we can query & listen without
// throwing too many requests at the server.
map.addListener('idle', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
keyword: 'best view'
};
service.radarSearch(request, callback);
}
function callback(results, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
addMarker(result);
}
}
function addMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
url: 'https://developers.google.com/maps/documentation/javascript/images/circle.png',
anchor: new google.maps.Point(10, 10),
scaledSize: new google.maps.Size(10, 17)
}
});
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(place, function(result, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
});
});
}
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCIcOfMnc85XkuJmotWkLL4mthAHqlUuWA&callback=initMap&libraries=places,visualization" async defer></script>
</body>
</html>
use a saved google my maps and share it from your google drive

Get current location on Google Map - AngularJS

I'm trying to get the current location using Google Map with AngularJS.
This is my code:-
angular.module('indexAngularApp', ['uiGmapgoogle-maps'])
.controller('mapsController', function($scope, $http) {
//this is default coordinates for the map when it loads for first time
var options = {
enableHighAccuracy: true
};
navigator.geolocation.getCurrentPosition(function(pos) {
$scope.map = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
$scope.map.center.latitude = new google.maps.LatLng(pos.coords.latitude);
$scope.map.center.longitude = new google.maps.LatLng(pos.coords.longitude);
$scope.map.center.zoom = 15;
//$scope.position.latitude = 28.699955;
//$scope.position.longitude = 77.098159;
//var a = $scope.position.latitude;
//var b = $scope.position.longitude;
//console.log(JSON.stringify($scope.map));
//$scope.map.center.latitude = $scope.position.latitude;
//$scope.map.center.longitude = data.data.Long;
// $scope.map =
//{
// center:
// {
// latitude: a,
// longitude: b
// },
// zoom: 15
//}
},
function(error) {
alert('Unable to get location: ' + error.message);
}, options);
$scope.markers = [];
$scope.locations = [];
//to get all the locations from the server
$http.get('http://localhost:4582/Api/NewCompWebAPI').then(function(data) {
$scope.locations = data.data;
}, function() {
alert('Error');
});
//service that gets makers info from server
$scope.ShowLocation = function(locationID) {
$http.get('/home/GetMarkerData', {
params: {
locationID: locationID
}
}).then(function(data) {
$scope.markers = [];
$scope.markers.push({
id: data.data.LocationID,
coords: {
latitude: data.data.Lat,
longitude: data.data.Long
},
title: data.data.title, //title of the makers
address: data.data.Address, //Address of the makers
image: data.data.ImagePath //image --optional
});
//set map focus to center
$scope.map.center.latitude = data.data.Lat;
$scope.map.center.longitude = data.data.Long;
}, function() {
alert('Error'); //shows error if connection lost or error occurs
});
}
//Show or Hide marker on map using options passes here
$scope.windowOptions = {
show: true
};
})
//mapsController Ends Here
<style>input {
padding: 5px;
border: 1px solid #A5A5A5;
}
input.ng-dirty.ng-invalid {
border: 1px solid red;
background-color: rgb(255, 244, 244);
}
.error {
color: red;
}
.angular-google-map-container {
height: 300px;
box-shadow: 2px 2px 3px 3px lightgrey;
}
.angular-google-map {
width: 80%;
height: 100%;
margin: auto 0px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyD7d5zEqURlPCFVM_NcsHLGSms_Pnu4-M4"></script>
<script src="//rawgit.com/angular-ui/angular-google-maps/2.0.X/dist/angular-google-maps.js"></script>
<div ng-app="indexAngularApp">
<!--Div for mapsController Upload Started-->
<div class="col-md-12">
<div ng-controller="mapsController">
<!--It displays the markers links-->
<div class="position">{{map.center}}</div>
<div class="maps">
<!-- Add directive code (gmap directive) for show map and markers-->
<ui-gmap-google-map style="box-shadow:2px 2px 2px 2px lightgrey; width:100%" center="map.center" zoom="map.zoom">
<ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
<ui-gmap-window options="windowOptions" show="windowOptions.show">
<div style="max-width:200px">
<div class="header"><strong>{{marker.title}}</strong></div>
<div id="mapcontent" class="container">
<p>
<img ng-src="{{marker.image}}" class="img-responsive" style="width:100%; height:200px" />
<div>{{marker.address}}</div>
<b>No of Customers:</b>
</p>
</div>
</div>
</ui-gmap-window>
</ui-gmap-marker>
</ui-gmap-google-map>
</div>
<hr />
<div class="locations">
<ul>
<li class="text-success" ng-repeat="l in locations" ng-click="ShowLocation(l.UniqueName)">{{l.UniqueName}}</li>
</ul>
</div>
</div>
</div>
<!--Div for mapsController Upload Ended-->
<div class="clearfix"></div>
Now the problem is I'm not able to get the current latitude and longitude of the device. Can anyone help me with this?
Finally I just changed the IndesAngular.js file :-
angular.module('indexAngularApp', ['uiGmapgoogle-maps'])
.controller('mapsController', function ($scope, $http) {
//this is default coordinates for the map when it loads for first time
var options = {
enableHighAccuracy: true
};
navigator.geolocation.getCurrentPosition(function (pos) {
$scope.position = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
$scope.map = {
center:
{
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
},
zoom:17
};
//console.log(JSON.stringify($scope.map));
},
function (error) {
alert('Unable to get location: ' + error.message);
}, options);
//$scope.map =
// {
// center:
// {
// latitude: 28.6315,
// longitude: 77.6315
// },
// zoom: 16
// }
$scope.markers = [];
$scope.locations = [];
//to get all the locations from the server
$http.get('http://localhost:4582/Api/NewCompWebAPI').then(function (data) {
$scope.locations = data.data;
}, function () {
alert('Error');
});
//service that gets makers info from server
//$scope.ShowLocation = function (locationID) {
// $http.get('/home/GetMarkerData',
// {
// params:
// {
// locationID: locationID
// }
// }).then(function (data) {
// $scope.markers = [];
// $scope.markers.push
// ({
// id: data.data.LocationID,
// coords:
// {
// latitude: data.data.Lat,
// longitude: data.data.Long
// },
// title: data.data.title, //title of the makers
// address: data.data.Address, //Address of the makers
// image: data.data.ImagePath //image --optional
// });
// //set map focus to center
// $scope.map.center.latitude = data.data.Lat;
// $scope.map.center.longitude = data.data.Long;
// }, function () {
// alert('Error'); //shows error if connection lost or error occurs
// });
//}
//Show or Hide marker on map using options passes here
$scope.windowOptions =
{
show: true
};
})
//mapsController Ends Here
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

OpenLayers 3 Polymer 1.0 module

I'm trying to make a Polymer module for working with OpenLayers 3 and displaying openstreetmaps. I know there is a great module working with leaflet but I need some specifics functions like map orientation.
Anyway, I code something and it's working except one thing I can't figure out : When the page loads, only the commands are showing (Zoom + / Zoom -) and not the map (and not any thing such as marker, etc). But if I resize my window (my Chrome window I mean) the map appear and all is working fine !! I was thinking maybe something in relation with DOM Loading...
Module code :
<dom-module id="openlayer-map">
<link rel="stylesheet" href="http://openlayers.org/en/v3.7.0/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.7.0/build/ol.js" type="text/javascript"></script>
<style>
:host {
display: block;
}
#map
{
position: absolute;
height: 100%;
}
</style>
<template>
<div id="map" class="map"></div>
<!-- Tests
<input is="iron-input" bind-value="{{latitude}}" placeholder="latitude">
<input is="iron-input" bind-value="{{longitude}}" placeholder="longitude">
-->
</template>
</dom-module>
<script>
(function() {
Polymer({
is: 'openlayer-map',
properties:
{
currentCenter: Array,
currentView: ol.View,
olmap: ol.Map,
geolocation: ol.Geolocation,
layer: Object,
longitude:
{
type: Number,
value:12.889101100000062,
notify: true,
observer: '_updateLongitude'
},
latitude:
{
type: Number,
value: 15.7622695,
notify: true,
observer: '_updateLatitude'
},
geotracking:
{
value: false,
type: Boolean,
notify: true,
},
elemReady: Boolean,
},
ready: function()
{
console.log('openlayer-map ready');
this.initialConfig();
this.elemReady = true;
this.setCenter(this.latitude,this.longitude);
},
initialConfig: function()
{
console.log('initial config for the map...');
this.currentView = new ol.View({
zoom: 14
});
var source = new ol.source.OSM();
this.layer = new ol.layer.Tile();
this.layer.setSource(source);
this.olmap = new ol.Map({
layers: [this.layer],
target: this.$.map,
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: this.currentView
});
// Localisation
this.geolocation = new ol.Geolocation({
projection: this.currentView.getProjection()
});
this.geolocation.setTracking(this.geotracking);
if(this.geolocation)
{
var accuracyFeature = new ol.Feature();
this.geolocation.on('change:accuracyGeometry', function() {
accuracyFeature.setGeometry(this.geolocation.getAccuracyGeometry());
}.bind(this));
var positionFeature = new ol.Feature();
positionFeature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#3399CC'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
}));
this.geolocation.on('change:position', function() {
var coordinates = this.geolocation.getPosition();
positionFeature.setGeometry(coordinates ?
new ol.geom.Point(coordinates) : null);
}.bind(this));
var featuresOverlay = new ol.layer.Vector({
map: this.olmap,
source: new ol.source.Vector({
features: [accuracyFeature, positionFeature]
})
});
}
},
_updateLatitude: function(newValue, oldValue)
{
if(this.elemReady)
{
console.log('update latitude from '+oldValue+' to '+newValue);
this.setCenter(newValue, this.longitude);
}
else
{
console.log('_updateLatitude: waiting element to be ready');
}
},
_updateLongitude: function(newValue, oldValue)
{
if(this.elemReady)
{
console.log('update longitude from '+oldValue+' to '+newValue);
this.setCenter(this.latitude, newValue);
}
else
{
console.log('_updateLatitude: waiting element to be ready');
}
},
setCenter: function(latitude, longitude)
{
var center = [longitude, latitude];
this.currentCenter = ol.proj.fromLonLat(center);
console.log('update center of the map with latitude = '+latitude+' and longitude = '+longitude);
this.currentView.centerOn(this.currentCenter,[400,400], [0,0]);
},
});
})();
</script>
And the call in Polymer :
<openlayer-map latitude="48.853" longitude="2.35" geotracking></openlayer-map>
Any clue ?
Found it ! Needed to do the map initialization in an asynchronous call
attached: function()
{
this.async(function()
{
this.initialConfig(); // Create your ol.Map here
});
},

Google Map direction line

I have this code that allows the user to enter two cities, and shows the location of the given inputs. But what I want is to show as well the direction from the 1st city to the other. How to do that?
Here is my practice code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBQ8OCC8En5vNHod25Ov3Qs5E1v7NPRSsg&sensor=true">
</script>
<script type="text/javascript">
var geocoder;
var map;
function initialize1() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 100.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function initialize() {
// add mapOptions here to the values in the input boxes.
var mapOptions = {
center: new google.maps.LatLng(-34.397, 100.644),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
geocoder = new google.maps.Geocoder();
addAddress(document.getElementById('from').value);
addAddress(document.getElementById('to').value);
}
function addAddress(place) {
var address = place;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
</head>
<body>
From: <input id="from" type="text" name="From"><br>
To: <input id="to" type="text" name="To"><br>
<button type="button" onclick="initialize()">View example (map-simple.html)</button>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
thanks
Jason
Use the DirectionsService in the Google Maps API v3. Here is an example from the documentation:
https://google-developers.appspot.com/maps/documentation/javascript/examples/directions-simple
and with text directions:
https://google-developers.appspot.com/maps/documentation/javascript/examples/directions-panel
if you mean the "location" means the address you can use the direction renderer like below to get the direction.
First of all store the location address of the two markers into the two text boxes if you want to display the to and from address with id's #from and #destination then follow the below code
$("#find").click(function () {
starting = $("#from").val();
finishing = $("#destination").val();
$("#map").gmap3(
{
action: 'getRoute',
options: {
origin: starting,
destination: finishing,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function (results) {
if (!results) {
alert("returning")
return
};
$(this).gmap3(
{
action: 'addDirectionsRenderer',
options: {
preserveViewport: true,
draggable: false,
directions: results
}
}
);
}
})
})
Explanation : At first I created two markers of different locations and different data then after the dragend of any marker there will be infowindow that shows the address and two buttons start and finish. I think you have done upto this part .
So after this I used two text boxes which will be filled according to the start button or finish button clicked .
After this if the user clicks the find button this text boxes values are used to find the direction between the two markers
Note: "here you can any marker for from or to only difference you have to maintain is to change the button clicked that is start or finish ....."
"You can even directly give the address in the text boxes and find the directions between them"
Here for whole manipulation I used gmap3 here is the code below that might help you
<script type="text/javascript">
window.onload = clear;
function clear() {
$("#from").val(null)
$("#destination").val(null)
}
$(document).ready(function () {
var starting = "";
var finishing = "";
$("#find").click(function () {
starting = $("#from").val();
finishing = $("#destination").val();
$("#map").gmap3(
{
action: 'getRoute',
options: {
origin: starting,
destination: finishing,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function (results) {
if (!results) {
alert("returning")
return
};
$(this).gmap3(
{
action: 'addDirectionsRenderer',
options: {
preserveViewport: true,
draggable: false,
directions: results
}
}
);
}
})
})
$("#map").gmap3({
action: 'addMarkers',
markers: [ //markers array
{lat: 22.74, lng: 83.28, data: 'madhu' },
{ lat: 17.74, lng: 82.28, data: 'raghu' }
],
map: { // this is for map options not for any markers
center: [17.74, 83.28],
zoom: 5
},
marker: {
options: {
draggable: true
},
events: {// marker events
dragend: function (marker, event, data) {
var contentString = '<div id="main content">'
+ '<input type="button" id="start" value="start" />'
+ '<input type="button" id="finish" value="finish" />'
+ '</div>';
//get address on click event
$(this).gmap3({
action: 'getAddress',
latLng: marker.getPosition(),
callback: function (results) {
var map = $(this).gmap3('get'),
infowindow = $(this).gmap3({ action: 'get', name: 'infowindow' })
if (infowindow) {
content = results && results[1] ? results && results[1].formatted_address : 'no address';
infowindow.open(map, marker);
infowindow.setContent(content + contentString);
}
else {
content = results && results[1] ? results && results[1].formatted_address : 'no address';
$(this).gmap3({
action: 'addinfowindow',
anchor: marker,
options: { content: content + contentString },
events: {
domready: function () {
$("#start").click(function () {
alert("start clicked " + content);
$("#from").val(content);
starting = content;
check();
})
$("#finish").click(function () {
alert("finish clicked " + content);
$("#destination").val(content);
finishing = content;
})
}
}
});
}
}
});
},
}
},
});
});
</script>
here is the html part for the above
<div id="headinput">
<input type="text" value="enter from" id="from" />
<input type="text" value="enter destination" id="destination" />
<input type="button" value="find" id="find" />
</div>
<br />
<div id ="map"style="width: 100%; top: auto; left: auto; position: relative; height: 600px; float:left" ></div>
This is perfectly worked one I checked it in firefox browser........:D

Categories