Related
I am trying to use the google maps details about a location to display in an info window from a marker. I am creating a marker and want to get the address of that marker so that I can store it in a database. I am able to get the title of the marker but I do not know how to get the full address. This is my code:
<script>
let pos;
let map;
let bounds;
let infoWindow;
let currentInfoWindow;
let service;
let infoPane;
function initMap() {
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow;
currentInfoWindow = infoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
bounds.extend(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
getNearbyPlaces(pos);
}, () => {
handleLocationError(true, infoWindow);
});
} else {
handleLocationError(false, infoWindow);
}
}
function handleLocationError(browserHasGeolocation, infoWindow) {
pos = { lat: -33.856, lng: 151.215 };
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Geolocation permissions denied. Using default location.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
currentInfoWindow = infoWindow;
getNearbyPlaces(pos);
}
function getNearbyPlaces(position) {
let request = {
location: position,
rankBy: google.maps.places.RankBy.DISTANCE,
keyword: 'basketball courts'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, nearbyCallback);
}
function nearbyCallback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
createMarkers(results);
}
}
function createMarkers(places) {
places.forEach(place => {
let marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
title: place.name
});
marker.addListener("click", () => {
map.setZoom(16);
map.setCenter(marker.getPosition());
});
bounds.extend(place.geometry.location);
});
map.fitBounds(bounds);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap">
</script>
I am unfamiliar with javascript so I am not sure how exactly to format it. If it shows up in the infowindow I can work on it myself from there but if anyone has suggestions on how to show it there I would appreciate it.
To be fair you have done most of the work but if it is simply a case of taking the results from the nearbyPlaces search and adding to an infowindow then perhaps you can find use in the following. The work is done in the createMarkers function
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Google Maps: </title>
<style>
#map{
width:800px;
height:600px;
float:none;
margin:auto;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
let pos;
let map;
let bounds;
let infoWindow;
let currentInfoWindow;
let service;
let infoPane;
function initMap() {
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow;
currentInfoWindow = infoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
bounds.extend(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
getNearbyPlaces( pos );
}, () => {
handleLocationError(true, infoWindow);
});
} else {
handleLocationError(false, infoWindow);
}
}
function handleLocationError(browserHasGeolocation, infoWindow) {
pos = { lat: -33.856, lng: 151.215 };
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Geolocation permissions denied. Using default location.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
currentInfoWindow = infoWindow;
getNearbyPlaces(pos);
}
function getNearbyPlaces(position) {
let request = {
location: position,
rankBy: google.maps.places.RankBy.DISTANCE,
keyword: 'basketball courts'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, nearbyCallback);
}
function nearbyCallback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
createMarkers(results);
}
}
function createMarkers(places) {
places.forEach(place => {
console.log(place)
let marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
title:place.name,
/* assign the response data as a property of the marker */
content:place
});
/*
for convenience a regular anonymous function is better here
as it allws us to use `this` to refer to the marker itself
within the body of the function.
*/
marker.addListener("click", function(e){
map.setZoom(16);
map.setCenter( marker.getPosition() );
/*
Iterate through ALL properties ( or just some ) of the `this.contents`
property and set as the content for the infowindow
*/
infoWindow.setContent( Object.keys(this.content).map(k=>{
return [k,this.content[k] ].join('=')
}).join( String.fromCharCode(10) ) );
/* open the infowindow */
infoWindow.setPosition(e.latLng)
infoWindow.open(map,this);
});
bounds.extend(place.geometry.location);
});
map.fitBounds(bounds);
}
</script>
<script async defer src="//maps.googleapis.com/maps/api/js?key=<APIKEY>&libraries=places&callback=initMap">
</script>
</body>
</html>
The data returned is JSON and has a structure like this for each individual result. The location data contained therein will bear no resemblance to that found for others running this self same script but show suffice.
{
"business_status" : "OPERATIONAL",
"geometry" : {
"location" : {
"lat" : 52.7525688,
"lng" : 0.4036446
},
"viewport" : {
"northeast" : {
"lat" : 52.75354047989272,
"lng" : 0.4048724298927222
},
"southwest" : {
"lat" : 52.75084082010728,
"lng" : 0.4021727701072778
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/generic_business-71.png",
"icon_background_color" : "#7B9EB0",
"icon_mask_base_uri" : "https://maps.gstatic.com/mapfiles/place_api/icons/v2/generic_pinlet",
"name" : "Multi-Use Games Area",
"place_id" : "ChIJX2Y4mjyL10cRQ0885NSSeTE",
"plus_code" : {
"compound_code" : "QC33+2F King's Lynn",
"global_code" : "9F42QC33+2F"
},
"rating" : 0,
"reference" : "ChIJX2Y4mjyL10cRQ0885NSSeTE",
"scope" : "GOOGLE",
"types" : [ "point_of_interest", "establishment" ],
"user_ratings_total" : 0,
"vicinity" : "The Walks, nr, South St, King's Lynn"
}
Within the marker click callback function, where previously there is this:
infoWindow.setContent( Object.keys(this.content).map(k=>{
return [k,this.content[k] ].join('=')
}).join( String.fromCharCode(10) ) );
We can build up a string of whatever items you wish to use:
infoWindow.setContent( this.content.name ); // simply display the name
or
infoWindow.setContent(
`<h1>${this.content.name}</h1>
<p>${this.content.vicinity}</p>
<ul>
<li>Lat: ${this.content.geometry.location.lat()}</li>
<li>Lng: ${this.content.geometry.location.lng()}</li>
</ul>
<img src="${this.content.icon}" />`
); // show some HTML content
Using react hooks and google maps API I have a code that puts a marker on the map but I don't know add show directions in this code. I searched but couldn't find a map example that includes both and also there is no definite google maps documentation for react hooks. I believe many other people are wondering this too, adding a marker and directions same map in react. I don't want to ask nonspecific questions but I have to. Thank you in advance
My goal is that the map component shows the location as a marker but I have directions too.
Only pins marker working code HERE
Here is my map component I've tried to implement directions but not worked.
MapTest.js
import { Fragment, useEffect, useState, useRef } from 'react';
import { useGoogleMaps } from 'react-hook-google-maps';
import {
withGoogleMap,
withScriptjs,
GoogleMap,
DirectionsRenderer,
} from 'react-google-maps';
const directions = [
{
lat: 35,
lng: -100,
},
{
lat: 36,
lng: -100,
},
];
const MapTest = () => {
const prevMarkersRef = useRef([]);
const [directions, setDirections] = useState('');
// incoming location to set
let point = {
lat: 34,
lng: -100,
};
// Map options
const { ref, map, google } = useGoogleMaps(
'YOUR API KEY',
{
zoom: 8,
center: point,
},
<DirectionsRenderer directions={directions} />
);
// directions
if (map) {
const directionsService = new google.maps.DirectionsService();
const origin = {
lat: 35,
lng: -100,
};
const destination = origin;
directionsService.route(
{
origin: origin,
destination: point,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: directions,
},
(result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
console.log(result);
setDirections(result);
} else {
console.error(`error fetching directions ${result}`);
}
}
);
}
useEffect(() => {
if (map) {
// ADD MARKER
const m = addMarker();
clearMarkers(prevMarkersRef.current); //clear prev markers
prevMarkersRef.current.push(m);
map.setCenter(point);
}
}, [point]);
// SIDE FUNCTIONS
function addMarker() {
return new window.google.maps.Marker({
position: point,
map: map,
});
}
function clearMarkers(markers) {
for (let m of markers) {
m.setMap(null);
}
}
return (
<div>
<div
ref={ref}
style={{ width: 400, height: 300 }}
/>
</div>
);
};
export default MapTest;
You can use the google.maps.DirectionsService() to call the Google Maps Directions API and google.maps.DirectionsRenderer() to display the directions to the map. You can instantiate them inside of your useEffect, bind the DirectionsRenderer to your map using setMap() then pass them in the function calcRoute(directionsService, directionsRenderer)` that will call the DirectionService:
useEffect(() => {
if (map) {
// ADD MARKER
const m = addMarker();
clearMarkers(prevMarkersRef.current); //clear prev markers
prevMarkersRef.current.push(m);
map.setCenter(point);
let directionsService = new google.maps.DirectionsService();
let directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
calcRoute(directionsService, directionsRenderer);
}
}, [point]);
For the calcRoute function, build the directions request by setting your origin, destination, mode and other parameters. Then pass them to the directionService.route to send the request. If the DirectionService result status is OK, show your result via the DirectionsRenderer:
function calcRoute(directionsService, directionsRenderer) {
let request = {
origin: point,
destination: dest,
travelMode: "DRIVING"
};
directionsService.route(request, function(result, status) {
if (status == "OK") {
directionsRenderer.setDirections(result);
}
});
}
Here is a sample working code.
I've searched high and low for proper documentation on how to configure Azure Maps with Angular and haven't found anything. How do I do this?
(Please look to the comments for my self-answered question)
As documentation for configuring Azure Maps with Angular does not exist, this post will accomplish that instead. By the end of this post, you should have a working Angular version of Azure Maps with map markers. Before adding any code, please follow the steps from the Microsoft website to set up your Azure Map keys: https://learn.microsoft.com/en-us/azure/azure-maps/
The first step to create your Azure Maps component is to create a new Angular component and add the following to your .html file:
<div id="azure-map"></div>
The id can be used for styling your component in the .scss file.
Next, we will work on the .ts file. First, let's set up the map. We'll add the following class variables for the map and coordinates:
map: any;
defaultLat: number = 47.608013; // Seattle coordinates
defaultLng: number = -122.335167;
and this output to emit coordinates to the map's parent component:
#Output() outputCoordinates: EventEmitter<number[]> = new EventEmitter<number[]>();
Now we will make a function called InitMap() and add this code snippet inside to initialize the base map and its properties:
this.map = new atlas.Map('azure-map', {
center: [this.defaultLng, this.defaultLat],
zoom: 12,
language: 'en-US',
showLogo: true,
showFeedbackLink: false,
dragRotateInteraction: false,
authOptions: {
authType: AuthenticationType.subscriptionKey,
subscriptionKey: 'YOUR_SUBSCRIPTION_KEY_HERE'
}
});
Next, we will add this code snippet inside InitMap() to register the map click hander and zoom controls:
this.map.events.add('ready', () => {
// Register the map click handler
this.map.events.add('click', (e) => {
this.outputCoordinates.emit([e.position[0], e.position[1]]); // 0 = longitude, 1 = latitude
});
//Construct a zoom control and add it to the map.
this.map.controls.add(new atlas.control.ZoomControl({
style: ControlStyle.auto,
zoomDelta: 1
}), {position: ControlPosition.BottomLeft});
});
We must also call the InitMap() function inside of ngOnInit().
The next step is to create the functionality to allow the user to drop and move pins on the map. This function will erase the current marker on the map, set the new marker's coordinates, initialize the marker drag handler, and set the boundaries of the map to track the newly placed pin marker. To handle all these operations, we will add this class variable:
markersReference: Marker[] = [];
and this function:
setMarkers(markers: Marker[]) {
if (markers && markers.length > 0) {
this.markersReference = markers;
this.map.markers.clear();
let boundsPositions: Array<{lng: number, lat:number}> = [];
for (let marker of markers) {
if (marker.latitude && marker.longitude) {
let htmlMarker = new atlas.HtmlMarker({
draggable: true,
position: [marker.longitude, marker.latitude] // longitude first
});
// Register the marker drag handler
this.map.events.add('dragend', htmlMarker, (e) => {
var pos = htmlMarker.getOptions().position;
this.outputCoordinates.emit([pos[0], pos[1]]); // 0 = longitude, 1 = latitude
});
boundsPositions.push({lng: marker.longitude, lat: marker.latitude}) // lat, lng
this.map.markers.add(htmlMarker);
}
}
this.map.setCamera({padding: {top: 20, bottom: 20, left: 20, right: 20}, maxZoom: 16,
bounds: atlas.data.BoundingBox.fromLatLngs(boundsPositions)});
}
Now we will add a function that allows us to center the map focus onto the dropped pin:
centerMapWithCoords(lon: number, lat: number) {
this.map.setCamera({zoom: 12, maxZoom: 16, center: [lon, lat]});
}
Lastly, in order to pick up changes that the user makes to the map, we will subscribe to the map subject and its markers. Add these inputs alongside your class variables:
#Input() markerDataSubject: Subject<Marker[]> = new Subject<Marker[]>();
#Input() centerMapSubject: Subject<{lng: number, lat: number}> = new Subject<{lng: number, lat: number}>();
Next, add these subscriptions to your ngOnInit():
this.subscriptions.push((this.centerMapSubject).asObservable().subscribe((coords) =>
this.centerMapWithCoords(coords.lng, coords.lat)));
this.subscriptions.push((this.markerDataSubject).asObservable().subscribe((markers) =>
this.setMarkers(markers)));
And unsubscribe when the component is closed:
ngOnDestroy() {
for (const s of this.subscriptions) {
s.unsubscribe();
}
}
Overall, the class in your .ts file should look similar to the following:
export class AzureMapComponent implements OnInit {
#Input() markerDataSubject: Subject<Marker[]> = new Subject<Marker[]>();
#Input() centerMapSubject: Subject<{lng: number, lat: number}> = new Subject<{lng: number, lat: number}>();
#Output() outputCoordinates: EventEmitter<number[]> = new EventEmitter<number[]>();
subscriptions: Subscription[] = [];
map: any;
markersReference: Marker[] = [];
defaultLat: number = 47.608013; // Seattle coordinates
defaultLng: number = -122.335167;
ngOnInit() {
this.InitMap();
this.subscriptions.push((this.centerMapSubject).asObservable().subscribe((coords) =>
this.centerMapWithCoords(coords.lng, coords.lat)));
this.subscriptions.push((this.markerDataSubject).asObservable().subscribe((markers) =>
this.setMarkers(markers)));
}
//Create an instance of the map control and set some options.
InitMap() {
this.map = new atlas.Map('azure-map', {
center: [this.defaultLng, this.defaultLat],
zoom: 12,
language: 'en-US',
showLogo: true,
showFeedbackLink: false,
dragRotateInteraction: false,
authOptions: {
authType: AuthenticationType.subscriptionKey,
subscriptionKey: 'YOUR_SUBSCRIPTION_KEY_HERE'
}
});
this.map.events.add('ready', () => {
// Register the map click handler
this.map.events.add('click', (e) => {
this.outputCoordinates.emit([e.position[0], e.position[1]]); // 0 = longitude, 1 = latitude
});
//Construct a zoom control and add it to the map.
this.map.controls.add(new atlas.control.ZoomControl({
style: ControlStyle.auto,
zoomDelta: 1
}), {position: ControlPosition.BottomLeft});
});
}
setMarkers(markers: Marker[]) {
if (markers && markers.length > 0) {
this.markersReference = markers;
this.map.markers.clear();
let boundsPositions: Array<{lng: number, lat:number}> = [];
for (let marker of markers) {
if (marker.latitude && marker.longitude) {
let htmlMarker = new atlas.HtmlMarker({
draggable: true,
position: [marker.longitude, marker.latitude] // longitude first
});
// Register the marker drag handler
this.map.events.add('dragend', htmlMarker, (e) => {
var pos = htmlMarker.getOptions().position;
this.outputCoordinates.emit([pos[0], pos[1]]); // 0 = longitude, 1 = latitude
});
boundsPositions.push({lng: marker.longitude, lat: marker.latitude}) // lat, lng
this.map.markers.add(htmlMarker);
}
}
this.map.setCamera({padding: {top: 20, bottom: 20, left: 20, right: 20}, maxZoom: 16,
bounds: atlas.data.BoundingBox.fromLatLngs(boundsPositions)});
}
}
centerMapWithCoords(lon: number, lat: number) {
this.map.setCamera({zoom: 12, maxZoom: 16, center: [lon, lat]});
}
ngOnDestroy() {
for (const s of this.subscriptions) {
s.unsubscribe();
}
}
}
Now that your Azure Maps component is complete, all you have to do is call an instance of your component within the .html of whatever view you'd like to place it in and coordinate the required inputs and output:
<app-azure-map
[markerDataSubject]="locationMarkerSubject"
[centerMapSubject]="centerMapSubject"
(outputCoordinates)="updateCoordinates($event)">
</app-azure-map>
The input subjects on your parent component should look something like this:
locationMarkerSubject: Subject<Marker[]> = new Subject<Marker[]>();
centerMapSubject: Subject<{lng: number, lat: number}> = new Subject<{lng: number, lat: number}>();
And your updateCoordinates() function will handle the marker data sent back from user input upon clicking the map.
I am trying to create a simple program that takes in specifically two specifically placed destinations and shows the directions in between them. For whatever reason, I just cannot get the directions to show up.
<script>
var directionsService = new google.maps.directionsService();
var directionsDisplay = new google.maps.directionsRenderer();
var new_york = {lat: 40.7128, lng: -74.0060};
var los_angeles = {lat: 34.0522, lng: -118.2437};
function initMap() {
var mapMarkers = [];
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: {lat: 40, lng: -99}}
);
var marker1 = new google.maps.Marker({
position: new_york,
map: map,
title: 'Home'
});
var marker2 = new google.maps.Marker({
position: los_angeles,
map: map,
title: 'School'
});
}
calculateAndDisplayRoute: function(directionsService, directionsDisplay, new_york, los_angeles) {
directionsService.route({
origin: new_york,
destination: los_angeles,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDmA98U4We-2IAaHbxa354v_C91IktiSKM3&callback=calculateAndDisplayRoute"></script>
I think there are a few problems with your code, first you need to be aware that the google maps library needs to be loaded before you can create new instances of DirectionsService and DirectionsRenderer, which btw should be in CamelCase:
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
Since you are not loading the maps library asynchronously you can place the script at the top of your page and just drop the callback argument. I've made a few changes to your code, please check it out below (you need to add your api key):
var new_york = {lat: 40.7128, lng: -74.0060};
var los_angeles = {lat: 34.0522, lng: -118.2437};
function initMap() {
var mapMarkers = [];
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: {lat: 40, lng: -99}}
);
var marker1 = new google.maps.Marker({
position: new_york,
map: map,
title: 'Home'
});
var marker2 = new google.maps.Marker({
position: los_angeles,
map: map,
title: 'School'
});
}
function calculateAndDisplayRoute() {
initMap();
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var route = {
origin: new_york,
destination: los_angeles,
travelMode: 'DRIVING'
};
directionsService.route(route, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
alert('Directions request failed due to ' + status);
}
});
}
calculateAndDisplayRoute();
<script src="https://maps.googleapis.com/maps/api/js?key=???"></script>
<div id="map" style="width: 100%; height: 500px;"></div>
I would like to create a link that open a new google map tab with route from navigator.geolocation.getCurrentPosition to a specific placeId.
If there is geolocation a problem then, open a new tab without origin completed
Here is what I try:
const options = {
placeId: 'ChIJDyx4bNhu5kcRqJ3RkAPGMEk',
latitude: 48.925606,
longitude: 2.327621,
};
const mapOptions = {
zoom: 15,
center: new google.maps.LatLng(options.latitude, options.longitude),
};
const map = new google.maps.Map(document.getElementById('Map'), mapOptions);
const service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: options.placeId,
}, (result, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
const marker = new google.maps.Marker({
map: map,
position: result.geometry.location,
});
});
$('.js-ItinaryFromI').on('click', () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
}, () => {
// The problem seems to come from this line :
window.open(`https://www.google.com/maps/dir/origin=pos&destination=place_id:${options.placeId}&travelmode=driving`, '_blank');
});
} else {
// And this line
window.open(`https://www.google.com/maps/dir//place_id${options.placeId}&travelmode=driving`, '_blank');
}
});
Any idea please ?
You should use Google Maps Directions API if you wanted to calculate directions between location. You can search for directions for several modes of transportation, including transit, driving, walking, or cycling.
These parameters (origin, destination, travel_mode) are used in Google Maps Directions API and probably won't work well using Google Maps.
I also noticed in the code you provided that certain variables were not properly concatenated into the request. Hence, your request would not provide accurate results.
Here's a sample of valid request:
window.open('https://maps.googleapis.com/maps/api/directions/json?origin='+pos.lat+','+pos.lng+'&destination=place_id:'+options.placeId+'&travelmode=driving&key=YOUR_API_KEY', '_blank');
Don't forget to include your API key in each request.
I modified your code a bit. You can check it below:
const options = {
placeId: 'ChIJDyx4bNhu5kcRqJ3RkAPGMEk',
//placeId: 'ChIJ51Ic7BXIlzMRK2WH8qoM6Ek',
latitude: 48.925606,
longitude: 2.327621,
};
function initMap() {
const mapOptions = {
zoom: 15,
center: new google.maps.LatLng(options.latitude, options.longitude),
};
const map = new google.maps.Map(document.getElementById('Map'), mapOptions);
const service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: options.placeId,
}, (result, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
const marker = new google.maps.Marker({
map: map,
position: result.geometry.location,
});
});
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition((position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
document.getElementById('js-ItinaryFromI').addEventListener('click', () => {
window.open('https://maps.googleapis.com/maps/api/directions/json?origin='+pos.lat+','+pos.lng+'&destination=place_id:'+options.placeId+'&travelmode=driving&key=[API-KEY]', '_blank');
});
});
} else {
alert('Geolocation not found!');
}
}
html,body,#Map {
width:100%;
height:100%;
}
<button id="js-ItinaryFromI">Click Me</button>
<div id="Map" ></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap&libraries=places">
</script>
You can try this using JSBin. For some reason it doesn't work here in Stackoverflow's code snippet. I don't know why.
Good luck and happy coding!