How to disable map zooming after rendering driving directions? - google-maps-api-3

Like title says - I want to avoid map zooming after rendering directions.
I found here a lot of about it, for example Do not change map center or zoom level when rendering directions, but after adding {preserveViewport: true} to DirectionsRenderer nothing happens.
I don't want to calculate the union of the bounds of the directions responses, but only 'freeze' while rendering directions. What am I doing wrong?
My map: https://jsfiddle.net/harlowpl/xawy71r0/33/
infoWindow = new google.maps.InfoWindow();
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true,
markerOptions: {
visible: false
}
});
createSourceMarker();
createDestinationMarkers();
}
function markerClicked(destinationLocation) {
var directionsRequest = {
origin: sourceLocation,
destination: destinationLocation,
travelMode: 'DRIVING'
};
directionsService.route(directionsRequest, handleDirectionResults);
}
function handleDirectionResults(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
} else {
console.log(status);
}
}
}
});

You have the zoom level set to a non-integer value. It is changing to an integer value when the directions result is displayed.
Hidden away in the documentation, it says: Specify zoom level as an integer.
proof of concept fiddle (setting zoom to 16, rather than 15.5)
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
<div id="map"></div>
<script>
var sourceLocation = {
lat: 52.340822,
lng: 16.855841
};
var destinationLocations = [{
lat: 52.344583,
lng: 16.849864
},
{
lat: 52.343319,
lng: 16.855080
},
];
var directionsService;
var directionsDisplay;
var infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 52.343580,
lng: 16.857495
},
zoom: 16,
styles: [{
"featureType": "poi",
"elementType": "all",
"stylers": [{
"visibility": "off"
}]
}],
gestureHandling: 'cooperative'
});
// console.log("zoom=" + map.getZoom());
// console.log("zoom=" + map.getZoom()+" bounds="+map.getBounds().toUrlValue());
google.maps.event.addListener(map, 'zoom_changed', function() {
console.log("zoom=" + map.getZoom());
});
google.maps.event.addListener(map, 'bounds_changed', function() {
console.log("zoom=" + map.getZoom() + " bounds=" + map.getBounds().toUrlValue());
});
infoWindow = new google.maps.InfoWindow();
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true,
markerOptions: {
visible: false
}
});
createSourceMarker();
createDestinationMarkers();
}
function markerClicked(destinationLocation) {
var directionsRequest = {
origin: sourceLocation,
destination: destinationLocation,
travelMode: 'DRIVING'
};
directionsService.route(directionsRequest, handleDirectionResults);
}
function handleDirectionResults(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
} else {
console.log(status);
}
}
function createSourceMarker() {
new google.maps.Marker({
position: sourceLocation,
map: map,
icon: 'http://nakujawskiej.pl/nk/wp-content/uploads/mapMarkers/marker-main.svg'
});
}
var opis = [
'<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<center><h4 id="firstHeading" class="firstHeading">Apteka</h4></center>' + '<hr>' +
'<div id="bodyContent">' +
'<p><b>Odległość :</b>' + ' 750m' + '<br>' + '<b>Czas dojazdu :</b>' + ' 2 min</p>' +
'</div>' +
'</div>',
'<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h4 id="firstHeading" class="firstHeading">Przedszkole</h4>' + '<hr>' +
'<div id="bodyContent">' +
'<p><b>Odległość :</b>' + ' 450m' + '<br>' + '<br>' + '<b>Czas dojazdu :</b>' + ' 2 min</p>' +
'</div>' +
'</div>',
];
var opisIndex = 0;
var iconBase = 'http://nakujawskiej.pl/nk/wp-content/uploads/mapMarkers/';
var markers = [
iconBase + 'marker-01.svg',
iconBase + 'marker-02.svg'
];
var markersIndex = 0;
function createDestinationMarkers() {
destinationLocations.forEach(function(location, index) {
var opisIndex = markersIndex;
var marker = new google.maps.Marker({
position: location,
map: map,
icon: markers[markersIndex++ % markers.length],
});
marker.addListener('click', function() {
infoWindow.setContent(opis[opisIndex % opis.length]);
infoWindow.open(map, marker);
});
marker.addListener('click', function() {
markerClicked(location);
});
})
}
// google.maps.event.addDomListener(window, "load", initMap);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDo5rkrpNDFQnr5Afq9fKGmGjOTPC0C390&callback=initMap" async defer></script>

Related

Google Map API InfoWindow click event not returning latlng

I created a polygon on google map and would like a infoWindow to pop up when I click on the polygon. Code as the follows:
google.maps.event.addListener(polygon, 'click', showVolume);
polygon_infoWindow = new google.maps.InfoWindow;
In the showVolume function,
function showVolume(event){
var polygon_Name = this.Name;
var volume = this.Volume;
var pt = event.latlng;
var contentString = '<b>Name: </b>' + polygon_Name + '<br>' + '<b>Volume: </b>' + volume + '<br>' + '<b>Clicked Location: </b>' + pt;
polygon_infoWindow.setContent(contentString);
polygon_infoWindow.open(map);
polygon_infoWindow.setPosition(pt);
}
The function returned the correct information belonging to the polygon. However it returned the event.latlng as undefined. I wonder what is wrong.
event.latlng doesn't exist, javascript is case sensitive, the property is event.latLng
proof of concept fiddle
code snippet:
var geocoder;
var map;
var polygon_infoWindow;
function initialize() {
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 polygon = new google.maps.Polygon({
map: map,
Name: "Fred",
Volume: 1000,
path: [{
lat: 37.4419,
lng: -122.1419
}, {
lat: 37.42,
lng: -122.16
}, {
lat: 37.4419,
lng: -122.1819
}]
});
google.maps.event.addListener(polygon, 'click', showVolume);
polygon_infoWindow = new google.maps.InfoWindow;
}
google.maps.event.addDomListener(window, "load", initialize);
function showVolume(event) {
var polygon_Name = this.Name;
var volume = this.Volume;
var pt = event.latLng;
var contentString = '<b>Name: </b>' + polygon_Name + '<br>' + '<b>Volume: </b>' + volume + '<br>' + '<b>Clicked Location: </b>' + pt;
polygon_infoWindow.setContent(contentString);
polygon_infoWindow.setPosition(pt);
polygon_infoWindow.open(map);
}
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>

Google Map Direction service Route

I want to draw the shortest path map route miles between the two points.Using the Javascript - directionsService.route
As click on first time map it creates start point as click second time on map it creates second point on it and draws route
var map;
var infowindow = new google.maps.InfoWindow();
var wayA;[![enter image description here][1]][1]
var wayB;
var geocoder = new google.maps.Geocoder();
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
panel: document.getElementById('right-panel'),
draggable: true
});
var directionsService = new google.maps.DirectionsService();
var data = {};
initMap();
function initMap() {
debugger;
map = new google.maps.Map(document.getElementById('rmap'), {
center: new google.maps.LatLng(23.030357, 72.517845),
zoom: 15
});
google.maps.event.addListener(map, "click", function (event) {
if (!wayA) {
wayA = new google.maps.Marker({
position: event.latLng,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=S|00FF00|000000"
});
} else {
if (!wayB) {
debugger;
wayB = new google.maps.Marker({
position: event.latLng,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=E|FF0000|000000"
});
calculateAndDisplayRoute(directionsService, directionsDisplay, wayA, wayB);
}
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
return total;
}
function computeTotalDuration(result) {
var total = 0;
var myroute = result.routes[0].legs[0].duration.text;
return myroute;
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, wayA, wayB) {
debugger;
directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
debugger;
calculateAndDisplayRoute(directionsService, directionsDisplay.getDirections(), wayA, wayB);
});
directionsService.route({
origin: wayA.getPosition(),
destination: wayB.getPosition(),
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function (response, status) {
if (status === 'OK') {
debugger;
var route = response.routes[0];
wayA.setMap(null);
wayB.setMap(null);
pinA = new google.maps.Marker({
position: route.legs[0].start_location,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=S|00FF00|000000"
}),
pinB = new google.maps.Marker({
position: route.legs[0].end_location,
map: map,
icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=E|FF0000|000000"
});
google.maps.event.addListener(pinA, 'click', function () {
infowindow.setContent("<b>Route Start Address = </b>" + route.legs[0].start_address + " <br/>" + route.legs[0].start_location);
infowindow.open(map, this);
});
google.maps.event.addListener(pinB, 'click', function () {
debugger;
infowindow.setContent("<b>Route End Address = </b>" + route.legs[0].end_address + " <br/><b>Distance=</b> " + computeTotalDistance(directionsDisplay.getDirections()) + " Km <br/><b>Travel time=</b> " + computeTotalDuration(directionsDisplay.getDirections()) + " <br/> " + route.legs[0].end_location);
infowindow.open(map, this);
});
} else {
window.alert('Directions request failed due to ' + status);
}
directionsDisplay.setDirections(response);
});
}

google map marker not defined wordpress

I am using the code below in the Ultimatum WordPress theme template along with some PHP code to provide the dynamic values required for the map. I am getting a marker not defined error. The code is placed 3/4 of the page down within div tags, rather than in the header or footer because it is only used on the one page. I've tried a couple of suggestions I found with no luck.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var geocoder;
var map;
function initialize ()
{
geocoder = new google.maps.Geocoder();
var address = document.getElementById('Property').value;
var city = document.getElementById('City').value;
var postal_code = document.getElementById('PostalCode').value;
var address_google_map = address + ', ' + city + ', ON ' + postal_code;
var myOptions =
{
zoom: 15,
mapTypeControl: true,
zoomControl: true,
zoomControlOptions:
{
style: google.maps.ZoomControlStyle.SMALL
},
StreetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var info_text = address + '<br />' + city + ' ON';
var info_window = new google.maps.InfoWindow
({
content: info_text
});
var map = new google.maps.Map(document.getElementById('google_map'), myOptions);
geocoder.geocode( { 'address': address_google_map}, 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);
}
});
google.maps.event.addListener(marker, 'click', function()
{
info_window.open(map, marker);
});
}
window.onload = function() {
initialize();
}
//]]>
</script>
The marker is local to the Geocoder callback routine. Move the click listener definition inside the function where it is in scope.
geocoder.geocode( { 'address': address_google_map}, 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
});
google.maps.event.addListener(marker, 'click', function()
{
info_window.open(map, marker);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

Open InfoWindow for each polygon google maps V3

Hope someone can help me with this issue.
I'm trying to open an info windows on click for each polygon that my users created.
I used the same code for a marker and works well but i couldn't make it work for each polygon.
Any thoughts on how to solve this problem?
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h2>Test</h2>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
// Show Areas
<?php foreach ($field->result() as $f):?>
// Create an array with the coordanates of each area
var field<?=$f->id?>Coords = [
<?php $latlng=$this->resources_data->field_latlng($f->id);?>
<?php foreach ($latlng->result() as $point):?>
new google.maps.LatLng(<?=$point->lat?>, <?=$point->lng?>),
<?php endforeach;?>
];
// Create a polygon with the points of the area
var area<?=$f->id?>=new google.maps.Polygon({
paths: area<?=$f->id?>Coords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
// Add the area to the map.
area<?=$f->id?>.setMap(map);
google.maps.event.addListener(area<?=$f->id?>,'click',function(){
infowindow.open(map,area<?=$f->id?>)
});
<?php endforeach;?>
You can't use the same form of InfoWindow.open for a polygon as you use for a marker (there is no marker to pass in).
From the documentation
open(map?:Map|StreetViewPanorama, anchor?:MVCObject)
Return Value: None
Opens this InfoWindow on the given map. Optionally, an InfoWindow can be associated with an anchor. In the core API, the only anchor is the Marker class. However, an anchor can be any MVCObject that exposes a LatLng position property and optionally a Point anchorPoint property for calculating the pixelOffset (see InfoWindowOptions). The anchorPoint is the offset from the anchor's position to the tip of the InfoWindow.)
You need to specifically set the place you want it to open when you call the open method (the latlng of the click is usually a good choice) with InfoWindow.setPosition().
Example
code snippet:
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function initialize() {
var geolib = google.maps.geometry.spherical;
var myOptions = {
zoom: 20,
center: new google.maps.LatLng(32.738158, -117.14874),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
bounds = new google.maps.LatLngBounds();
var polygon1 = new google.maps.Polygon({
map: map,
path: [geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 0),
geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 120),
geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, -120)
],
name: "polygon1"
});
google.maps.event.addListener(polygon1, 'click', function(event) {
var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
for (var i = 0; i < polygon1.getPath().getLength(); i++) {
bounds.extend(polygon1.getPath().getAt(i));
}
var polygon2 = new google.maps.Polygon({
map: map,
path: [geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 180),
geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 60),
geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, -60)
],
name: "polygon2"
});
google.maps.event.addListener(polygon2, 'click', function(event) {
var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
for (var i = 0; i < polygon2.getPath().getLength(); i++) {
bounds.extend(polygon2.getPath().getAt(i));
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
function createClickablePoly(poly, html, label, point) {
gpolys.push(poly);
if (!point && poly.getPath && poly.getPath().getLength && (poly.getPath().getLength > 0) && poly.getPath().getAt(0)) {
point = poly.getPath().getAt(0);
}
var poly_num = gpolys.length - 1;
if (!html) {
html = "";
} else {
html += "<br>";
}
var length = poly.Distance();
if (length > 1000) {
html += "length=" + poly.Distance().toFixed(3) / 1000 + " km";
} else {
html += "length=" + poly.Distance().toFixed(3) + " meters";
}
for (var i = 0; i < poly.getPath().getLength(); i++) {
html += "<br>poly[" + poly_num + "][" + i + "]=" + poly.getPath().getAt(i);
}
html += "<br>Area: " + poly.Area() + " sq meters";
// html += poly.getLength().toFixed(2)+" m; "+(poly.getLength()*3.2808399).toFixed(2)+" ft; ";
// html += (poly.getLength()*0.000621371192).toFixed(2)+" miles";
var contentString = html;
google.maps.event.addListener(poly, 'click', function(event) {
infowindow.setContent(contentString);
if (event) {
point = event.latLng;
}
infowindow.setPosition(point);
infowindow.open(map);
// map.openInfoWindowHtml(point,html);
});
if (!label) {
label = "polyline #" + poly_num;
}
label = "<a href='javascript:google.maps.event.trigger(gpolys[" + poly_num + "],\"click\");'>" + label + "</a>";
// add a line to the sidebar html
// side_bar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+');">' + label + '<br />';
}
body,
html {
height: 100%;
width: 100%;
}
<script src="https://maps.google.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<table border="1" style="height:100%; width:100%">
<tr>
<td>
<div id="map_canvas" style="width:100%; height:100%"></div>
</td>
<td width="200">
<div id="report"></div>
</td>
</tr>
</table>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 45.15492713361847, lng: 15.40557861328125}
});
var polygons = [{name: 'first name', coordinates:[{lat:45.15492713361847,lng:15.40557861328125},{lat:45.07933920973809,lng:15.5291748046875},{lat:45.01918507438175,lng:15.43304443359375},{lat:45.07933920973809,lng:15.3204345703125}]}];
// foreach your polygons
for (var i = 0; i < polygons.length; i++) {
var item = polygons[i];
var coors = item["coordinates"];
var name = item["name"];
var Polygon = new google.maps.Polygon({
path: coors,
strokeColor: '#66b3ff',
strokeOpacity: 0.8,
strokeWeight: 5,
editable: false,
fillColor: 'blue',
fillOpacity: 0.5,
});
Polygon.setMap(map);
// call function to set window
attachPolygonInfoWindow(Polygon, coors, name);
}
}
function attachPolygonInfoWindow(polygon, coors, html)
{
polygon.infoWindow = new google.maps.InfoWindow({
content: html
});
polygon.infoWindow.setPosition(getHighestWindowPosition(coors));
google.maps.event.addListener(polygon, 'mouseover', function () {
polygon.infoWindow.open(map, polygon);
});
google.maps.event.addListener(polygon, 'mouseout', function () {
polygon.infoWindow.close();
});
}
// function to get highest position of polygon to show window nice on top
function getHighestWindowPosition(coors) {
var lat = -5000, lng = 0, i = 0, n = coors.length;
for (; i !== n; ++i) {
if (coors[i].lat > lat) {
lat = coors[i].lat;
lng = coors[i].lng;
}
}
return {lat: lat, lng: lng};
}
</script>

Google place Api PlaceDetails

Hi the below code gives the place search , but it is showing only names i want the complete details of the places in the infobox..the below code isprovided by DR.Molle
http://jsfiddle.net/doktormolle/C5ZtK/
below is the code for retrieving the placedetails but not able to make it working
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
infowindow.open(map, this);
});
});
}
i checked the developers page but not able to get much from it Any help would be appreciated
Example that gets the place details for the clicked marker:
http://www.geocodezip.com/v3_GoogleEx_place-search_starbucks3.html
code snippet:
var geocoder = null;
var map;
var service;
var infowindow;
var gmarkers = [];
var bounds = null;
function initialize() {
geocoder = new google.maps.Geocoder();
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
geocoder.geocode({
'address': "Seattle, WA"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point = results[0].geometry.location;
bounds = results[0].geometry.viewport;
var rectangle = new google.maps.Rectangle({
bounds: bounds,
fillColor: "#FF0000",
fillOpacity: 0.4,
strokeColor: "#0000FF",
strokeWeigth: 2,
strokeOpacity: 0.9,
map: map
});
map.fitBounds(bounds);
var request = {
bounds: bounds,
name: "starbucks",
types: ['establishment']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
contentStr += '<br>' + place.types + '</p>';
infowindow.setContent(contentStr);
infowindow.open(map, marker);
}
});
});
gmarkers.push(marker);
var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
document.getElementById('side_bar').innerHTML += side_bar_html;
}
function openInfoWindow(id) {
return true;
}
google.maps.event.addDomListener(window, 'load', initialize);
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<table border="1">
<tr>
<td>
<div id="map"></div>
</td>
<td>
<div id="side_bar"></div>
</td>
</tr>
</table>

Resources