Google Maps API Directions Not Showing Map - google-maps

Using Google Maps Directions API, this was able to work previously.
Just to clarify... The directions work, but not the Map image background:
JavaScript Code:
function initMap() {
var myLatLng = {lat: 34.072350, lng: -118.401209};
var directionsService = new google.maps.DirectionsService();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 19,
center: myLatLng
});
var directionsDisplay = new google.maps.DirectionsRenderer();
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Wallis Annenberg Center for the Performing Arts'
});
directionsDisplay.setMap(map);
var onChangeHandler = function () {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: document.getElementById('start').value,
destination: "9390 N. Santa Monica Blvd. Beverly Hills, CA 90210",
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
HTML and CSS codes:
<style type="text/css">
#map {width:1050px;height:500px;}
</style>
<div id="map"></div>
Trying to follow this :
https://developers.google.com/maps/documentation/javascript/examples/directions-simple
For this site:
http://thewallis.org/directionsandparking.php
Here's what it looks like:
Edit
Some things that I did not see... _custom.css manipulates the responsiveness of Google Maps image to become important. Here's a sample code that affected the problem:
#map {width:1050px !important;height:500px !important;}

Your styles for .inner-section img:first-child also affect the images used by the maps-API. Find another selector(which doesn't affect the images in the map) or override these styles for the images in the map

Related

Convert address into coordinates for Google Maps Local Context (Geocoding + Local Context Maps)

I am attempting to plug Google Maps Local Context into my website, and I am looking to use an address string (1234 Main St, City, State, USA) to center and display a marker on my map.
Here's the code I have that displays a simple map on the site, but I need help getting an address to work instead of coordinates.
I have to use Geocoder, but I need help tying it together with the Google Maps Local Context map.
let map;
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: ["restaurant", "tourist_attraction"],
maxPlaceCount: 12,
});
const center = { lat: 37.4219998, lng: -122.0840572 };
map = localContextMapView.map;
new google.maps.Marker({ position: center, map: map });
map.setOptions({
center: center,
zoom: 14,
});
}
https://jsfiddle.net/cegytdj6/
code snippet:*
let map;
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: ["restaurant", "tourist_attraction"],
maxPlaceCount: 12,
});
const center = {
lat: 37.4219998,
lng: -122.0840572
};
map = localContextMapView.map;
new google.maps.Marker({
position: center,
map: map
});
map.setOptions({
center: center,
zoom: 14,
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Local Context Basic</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=localContext&v=beta" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
</body>
</html>
See the simple geocoder example for how to use the geocoder in the Google Maps Javascript API v3.
The code below will use the geocoder to return the coordinates for "1600 Amphitheatre Parkway, Mountain View, CA".
let geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: "1600 Amphitheatre Parkway, Mountain View, CA" }, (results, status) => {
if (status === "OK") {
const center = results[0].geometry.location;
map.setCenter(center);
new google.maps.Marker({ position: center, map: map });
map.setOptions({
center: center,
zoom: 14,
});
putting that into your existing code:
let map;
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: ["restaurant", "tourist_attraction"],
maxPlaceCount: 12,
});
map = localContextMapView.map;
let geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: "1600 Amphitheatre Parkway, Mountain View, CA"
}, (results, status) => {
if (status === "OK") {
const center = results[0].geometry.location;
map.setCenter(center);
new google.maps.Marker({
position: center,
map: map
});
map.setOptions({
center: center,
zoom: 14,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
updated fiddle
code snippet:
let map;
function initMap() {
const localContextMapView = new google.maps.localContext.LocalContextMapView({
element: document.getElementById("map"),
placeTypePreferences: ["restaurant", "tourist_attraction"],
maxPlaceCount: 12,
});
map = localContextMapView.map;
let geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: "1600 Amphitheatre Parkway, Mountain View, CA"
}, (results, status) => {
if (status === "OK") {
const center = results[0].geometry.location;
map.setCenter(center);
new google.maps.Marker({
position: center,
map: map
});
map.setOptions({
center: center,
zoom: 14,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Local Context Basic</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=localContext&v=beta" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
</body>
</html>
Seems like you already have address and you just need to use geocoding API to convert the address into coordinates.
Inside of your script, you need to get geocoding API CDN with reloading the page. I will use axios to do that. Here is the code;
Add these two lines in the head of your HTML page.
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
Now you can make AJAX request using axios.
Inside your script;
axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=Your_address&key=YOUR_API_KEY`)
.then(response => {
var lt = response.geometry.location.lat;
var ln = response.geometry.location.lng;
map.setCenter({lat: lt, lng:ln});
marker.setCenter({lat: lt, lng: ln});
})
.catch(error => {
console.log(error) //or whatever you want
})

Google Streetview API returns a different view than google.com/maps. Any workaround?

So I noticed that google.com/maps provides a different StreetView than my Streetview API with the combination of geolocator.
To show you an example, we will use the following address:
2510 Cherry Valley Blvd Dallas, TX 75241
When getting coordinates of this address, I use the following geocode api:
http://maps.google.com/maps/api/geocode/json?address=2510+Cherry+Valley+Blvd+Dallas,+TX+75241
It returns the following location:
{ lat: 32.6432887, lng: -96.7823027 }
I then use these coordinates in my Google Streetview API.
However, when I go on google.com/maps, enter the same address and go to streetview, it ends up with slightly different coordinates that better represent the front face of the business address. In this case, the coordinates that it uses are the following:
{lat: 32.6439611, lng: -96.7825014}
https://www.google.com/maps
Below are two images (first the result with Google Maps API, and the second result is with google.com/maps.
How do I make sure that the view returned on my page with Google Maps API is exactly the same as that on google.com/maps?
My client needs this. Any ideas on how to adjust geolocator API or Google Maps API would be greatly appreciated.
My Google Maps API returns the following image (for some reason the view is on the adjecent street, and as a result is slightly incorrect):
Google.com/maps returns the following image (address says 2519 Cherry Valley even though I searched for 2510 Cherry Valley). Google api seems to adjust geolocation for more accurate view.
One option is to snap the streetview using the DirectionsService, which returns the place you would drive to.
proof of concept fiddle
code snippet:
var map;
var sv = new google.maps.StreetViewService();
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();
var panorama;
var address;
function initialize() {
panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"));
myLatLng = new google.maps.LatLng(37.422104808, -122.0838851);
var myOptions = {
zoom: 15,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
address = "2510 Cherry Valley Blvd Dallas, TX 75241";
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myLatLng = results[0].geometry.location;
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
map.setCenter(myLatLng);
// find a Streetview location on the road
var request = {
origin: address,
destination: address,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, directionsCallback);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
sv.getPanoramaByLocation(myLatLng, 50, processSVData);
// getPanoramaByLocation will return the nearest pano when the
// given radius is 50 meters or less.
google.maps.event.addListener(map, 'click', function(event) {
sv.getPanoramaByLocation(event.latLng, 50, processSVData);
});
}
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var marker = new google.maps.Marker({
position: data.location.latLng,
draggable: true,
map: map,
title: data.location.description
});
panorama.setPano(data.location.pano);
var heading = google.maps.geometry.spherical.computeHeading(data.location.latLng, myLatLng);
panorama.setPov({
heading: heading,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
google.maps.event.addListener(marker, 'click', function() {
var markerPanoID = data.location.pano;
// Set the Pano to use the passed panoID
panorama.setPano(markerPanoID);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
});
} else {
alert("Street View data not found for this location.");
}
}
function geocoderCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
map.setCenter(latlng);
sv.getPanoramaByLocation(latlng, 50, processSVData);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
};
function directionsCallback(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var latlng = response.routes[0].legs[0].start_location;
map.setCenter(latlng);
sv.getPanoramaByLocation(latlng, 50, processSVData);
} else {
alert("Directions service not successfull for the following reason:" + status);
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body {
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="pano" style="width: 100%; height: 400px;"></div>
<div id="map_canvas" style="width: 100%; height: 400px;"></div>

Google Maps API route response different than the original coordinates

I'm working with Google Maps to show a cars last location. Often times this will be in a parking lot off of a main road, however when I input the coordinates for the parking lot carLatLng into Google's routing engine the response I get looks to be the nearest road. How do I get it so that the same coordinates I enter are the ones I get from my response?
var carLatLng = new google.maps.LatLng(29.9461,-90.07)
var request = {
origin: carLatLng,
destination:
waypoints: [],
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.WALKING
};
self.directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var lat = response.routes[0].legs[0].end_location.lat();
var lng = response.routes[0].legs[0].end_location.lng();
// lat = 29.946164
// lng = -90.0702933
}
});
The DirectionsService always returns start/end points for driving directions on the road. If you want the result to end somewhere else, you need to extend the polyline yourself (you have the original coordinates, draw a polyline from there to the end of the route from the directions service).
proof of concept fiddle
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var carLatLng = new google.maps.LatLng(29.9461, -90.07);
var carMarker = new google.maps.Marker({
map: map,
position: carLatLng
});
var request = {
origin: "Dixon, New Orleans, LA",
destination: carLatLng,
waypoints: [],
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.WALKING
};
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true,
polylineOptions: {
strokeColor: "#0000FF"
}
})
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var lat = response.routes[0].legs[0].end_location.lat();
var lng = response.routes[0].legs[0].end_location.lng();
directionsRenderer.setDirections(response);
map.setCenter(carLatLng);
map.setZoom(20);
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "#0000FF",
path: [carLatLng, response.routes[0].legs[0].end_location]
});
// lat = 29.946164
// lng = -90.0702933
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
I've done a lot lately with Google Map API, unfortunately not with the routing service.
But have a look at these tutorials, they are quite detailed, I found them very helpful at times: http://econym.org.uk/gmap/
For your case I'd especially look at part 26 onwards.

Hide polyline from A to B using in Google Map api v3

I am displaying google map with code below, I want to hide Polyline between A to B. All answers on google talk about creating an array and then doing array.setmap(null). can I hide polyline without using arrays. In other case, how should I use array to hide polyline using code below.
Edit: I need marker A and B to be shown
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var time;
function initialize() {
var rendererOptions = {
map: map,
draggable: true
}
// Instantiate a directions service.
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// Create a map and center it on islamabad.
var islamabad = new google.maps.LatLng(33.7167, 73.0667);
var mapOptions = {
zoom: 13,
center: islamabad
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = document.getElementById('MainContent_txtFrom').value;
var end = document.getElementById('MainContent_txtTo').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
If you want to render the directions but hide the polyline, use the DirectionsRendererOptions suppressPolylines.
function initialize() {
var rendererOptions = {
suppressPolylines: true,
map: map,
draggable: true
}
// Instantiate a directions service.
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
As shown in the demo below, you can remove polylines by two means:
setting the option suppressPolylines to true in directionsDisplay, your google.maps.DirectionsRenderer by using
directionsDisplay.setOptions({
suppressPolylines: true
});
This will preserve the start- and end-point markers.
The method setOptions(options:DirectionsRendererOptions) changes the options settings of DirectionsRenderer after initialization.
use directionsDisplay.setMap(null); to remove all directions rendering, but this includes markers, so if you do that you will need to add extra markers to the map.
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var time;
var pointA = new google.maps.LatLng(48.86, 2.35);
var pointB = new google.maps.LatLng(33.7167, 73.0667);
function initialize() {
var rendererOptions = {
map: map,
draggable: true
}
// Instantiate a directions service.
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
// Create a map and center it on islamabad.
var islamabad = new google.maps.LatLng(33.7167, 73.0667);
var mapOptions = {
zoom: 13,
center: islamabad
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = pointA;
var end = pointB;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
};
function removeRoute() {
directionsDisplay.setOptions({
suppressPolylines: true
});
// this "refreshes" the renderer
directionsDisplay.setMap(map);
};
function removeRouteNull() {
directionsDisplay.setMap(null);
};
google.maps.event.addDomListener(window, 'load', initialize);
#map {
height: 280px;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<button onclick="removeRoute()">Remove route (suppressPolylines)</button>
<button onclick="removeRouteNull()">Remove route (setMap(null))</button>
<button onclick="initialize()">Undo all</button>
<section id="map"></section>
If you refer to this answer: Google Maps v3 directionsRenderer.setMap(null) not working to clear previous directions you should see what you're looking for.
You do not need to use an array as you're implementing the directionsRenderer object. If you declare this globally (Edit Which I now see you have already) (so that you only have one instance at any given time) then you can simply use directionsDisplay.setMap(null) to remove previous directions rendered.
If you want to render the markers from the response but hide the polyline I suppose the simplest (but I would imagine by no means cleanest) way would be to simply alter the opacity on the polyline object:
var myPolylineOptions = new google.maps.Polyline({
strokeColor: '#FF0000',
strokeOpacity: 0.00001,
strokeWeight: 0
});
And then assign it to your renderer:
directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions: myPolylineOptions});

Why won't google map navigate on my web page?

I want to locate a user's location using Geolocation and then navigate between user;s position and a fix point, but Google map just won't navigate and I am using the codes from Google's official documentation!
What's wrong? I am going mad after tried thousands of times,plz help
<script type="text/javascript">
$( "#map-page" ).live( "pageinit", function() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var salon = new google.maps.LatLng(22.981666,120.194301);
var defaultLatLng = new google.maps.LatLng(22.983587,120.22599); // Default to Hollywood, CA when no geolocation support
if ( navigator.geolocation ) {
function success(pos) {
// Location found, show map with these coordinates
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
calcRoute(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
console.log(error);
drawMap(defaultLatLng); // Failed to find location, show default map
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
} else {
drawMap(defaultLatLng); // No geolocation support, show default map
}
function drawMap(latlng) {
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Greetings!"
});
var marker = new google.maps.Marker({
position:new google.maps.LatLng(22.981666,120.194301),
map:map,
title:"the salon"
});
}
function calcRoute(latlng) {
var start = latlng;
var end = new google.maps.LatLng(22.981666,120.194301);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
});
</script>
You forgot to setup directionsDisplay.