I have created the following code using Google Maps API that should make a direction line on Google Maps between two given addresses. My Code is:
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var geocoder = new google.maps.Geocoder();
var pointA,pointB;
geocoder.geocode({'address': document.getElementById('addressFrom').value}, function(results, status) {
var location = results[0].geometry.location;
pointA = new google.maps.LatLng(location.lat(),location.lng());
alert(location.lat() + '' + location.lng());
});
geocoder.geocode({'address': document.getElementById('addressTo').value}, function(results, status) {
var location = results[0].geometry.location;
pointB = new google.maps.LatLng(location.lat(),location.lng());
alert(location.lat() + '' + location.lng());
});
var markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
});
var markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
});
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
directionsService.route({
origin: pointA,
destination: pointB,
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);
}
});
}
<input id="addressFrom" type="textbox" value="Sydney">
<input id="addressTo" type="textbox" value="London">
<input id="submit" type="button" value="Geocode" onclick="initMap">
<div id="map"></div>
I get the following errors when inspecting from the browser:
The geocoder is asynchronous, the results don't come back until after you place the call to the directions service.
A hint is this error in the javascript console: Uncaught TypeError: Cannot read property 'l' of null
Chain the geocoder calls (not sure why you need those, the directions service takes addresses just fine), move the call to the directions service into the callback function for the second geocode operation (so both locations are available when the directions service is called).
Another problem is you can't drive from Sydney to London.
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {
lat: -34.397,
lng: 150.644
}
});
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var geocoder = new google.maps.Geocoder();
var pointA, pointB;
geocoder.geocode({
'address': document.getElementById('addressFrom').value
}, function(results, status) {
if (status != "OK") return;
var location = results[0].geometry.location;
pointA = new google.maps.LatLng(location.lat(), location.lng());
alert(location.lat() + ',' + location.lng());
var markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
});
geocoder.geocode({
'address': document.getElementById('addressTo').value
}, function(results, status) {
if (status != "OK") return;
var location = results[0].geometry.location;
pointB = new google.maps.LatLng(location.lat(), location.lng());
alert(location.lat() + ',' + location.lng());
var markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
});
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);
});
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
directionsService.route({
origin: pointA,
destination: pointB,
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,
body,
#map {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="addressFrom" type="textbox" value="Sydney" />
<input id="addressTo" type="textbox" value="London" />
<input id="submit" type="button" value="Geocode" onclick="initMap()" />
<div id="map"></div>
When you call the function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB); the positions pointAand pointB are undefined because they are the result of the asyncronous call of geocoder.geocode.
Move the calculateAndDisplayRoute function call after you've obtained a result from geocoder.geocode
geocoder.geocode({
'address': document.getElementById('addressTo').value
}, function(results, status) {
var location = results[0].geometry.location;
poi
if (status == google.maps.GeocoderStatus.OK) {
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);
}
Since you're sending two geocoding requests you will need to wait for the geocoder status for each request.
Related
here is a picture with the problem.
I am using Vue.js to consume a REST API that send data about upcoming bus transfers. In the picture above each list item represents a transfer and when clicked, the map should show the route. When switching from smaller to bigger is okay, but then when I switch to a shorter route, the blue line indicating it appears blurred and bigger than normal. The problem disappears when I zoom in/out, it's just the initial display.
I've tried the setZoom(int) function on the map object after every new request, but that didn't work.
Here's the relevant code from the Vue instance:
methods: {
...
calcRoute() {
const request = {
origin: this.start,
destination: this.end
}
this.directionsService.route(request, (result, status) => {
if (status == 'OK') {
this.directionsRenderer.setDirections(result);
//this.map.setZoom(12);
}
})
}
},
watch: {
start: () => {
if (this.end && this.start) {
this.calcRoute();
}
},
...
}
EDIT: as suggested, I've provided a running code snippet. Click the CHANGE DIRECTIONS button to see the problem.
EDIT 2: I've implemented it in pure JS for simplicity
EDIT 3: Provide your API KEY
const transfers = [{
"id": 29,
"date": "2020-02-12T08:00:00.000Z",
"pick_up": "Sofia Airport, Terminal 1",
"drop_off": "Stara Zagora",
"driver": "СТ",
"vehicle": 6264,
},
{
"id": 43,
"date": "2020-02-13T08:30:00.000Z",
"pick_up": "Sofia Terminal 1",
"drop_off": "Boutique One Hotel Sofia",
"driver": "СТ",
"vehicle": 6264,
}];
let map, directionsService, directionsRenderer;
let selectedTrans = 0;
window.addEventListener('load', function() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: 7,
center: {
lat: 42.698334,
lng: 23.319941
}
});
directionsService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
calcRoute();
});
function calcRoute() {
const start = transfers[selectedTrans].pick_up;
const end= transfers[selectedTrans].drop_off;
const request = {
origin: start,
destination: end,
travelMode: 'DRIVING'
};
directionsService.route(request, (result, status) => {
if (status == 'OK') {
directionsRenderer.setDirections(result);
}
})
}
document.getElementById('changeDirectionsBtn').addEventListener('click', () => {
selectedTrans = selectedTrans == 0 ? 1 : 0;
calcRoute();
});
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<button id="changeDirectionsBtn"> Change Directions </button>
<div id="map">
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" defer></script>
I'd need to investigate this a bit further when I have some time...
The documentation mentions that
Because the renderer is an MVCObject, it will automatically detect any changes to its properties and update the map when its associated directions have changed.
and I am not sure about what that exactly means.
That said, simply calling directionsRenderer.setMap(null); before calculating the new route and directionsRenderer.setMap(map); in the callback fixes the issue. See the snippet below.
const transfers = [{
"id": 29,
"date": "2020-02-12T08:00:00.000Z",
"pick_up": "Sofia Airport, Terminal 1",
"drop_off": "Stara Zagora",
"driver": "СТ",
"vehicle": 6264,
},
{
"id": 43,
"date": "2020-02-13T08:30:00.000Z",
"pick_up": "Sofia Terminal 1",
"drop_off": "Boutique One Hotel Sofia",
"driver": "СТ",
"vehicle": 6264,
}];
let map, directionsService, directionsRenderer;
let selectedTrans = 0;
window.addEventListener('load', function() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: 7,
center: {
lat: 42.698334,
lng: 23.319941
}
});
directionsService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer();
calcRoute();
});
function calcRoute() {
directionsRenderer.setMap(null);
const start = transfers[selectedTrans].pick_up;
const end= transfers[selectedTrans].drop_off;
const request = {
origin: start,
destination: end,
travelMode: 'DRIVING'
};
directionsService.route(request, (result, status) => {
if (status == 'OK') {
directionsRenderer.setDirections(result);
directionsRenderer.setMap(map);
}
})
}
document.getElementById('changeDirectionsBtn').addEventListener('click', () => {
selectedTrans = selectedTrans == 0 ? 1 : 0;
calcRoute();
});
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<button id="changeDirectionsBtn"> Change Directions </button>
<div id="map">
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" defer></script>
I'm going to initalize infowindows (for google map markers) through angular controller (i'm using ng-map module)
NgMap.getMap().then (map) ->
$scope.map = map
for marker in markers
latLng = new (google.maps.LatLng)(marker.latitude, marker.longitude)
#initialize infoWindows through google map api, not ng-map module
contentString = 'is an example string'
infoWindow = new (google.maps.InfoWindow)(content: contentString)
$scope.dynMarkers.push new (google.maps.Marker)(position: latLng)
marker.addListener 'click', ->
infoWindow.open map, marker
$scope.markerClusterer = new MarkerClusterer(map,$scope.dynMarkers, {})
I have an error in console:
marker.addListener is not a function
I can't use an ng-map 'infowindow' DOM element in my view.
What's wrong?
marker object needs to be of google.maps.Marker type, try to replace:
$scope.dynMarkers.push new (google.maps.Marker)(position: latLng)
marker.addListener 'click', ->
infoWindow.open map, marker
with
markerObject = new (google.maps.Marker)(position: latLng) #<-Marker object
$scope.dynMarkers.push markerObject
markerObject.addListener 'click', ->
infoWindow.open map, markerObject
Example
angular.module('mapApp', ['ngMap'])
.controller('mapController', function ($scope, NgMap) {
NgMap.getMap().then(function (map) {
$scope.map = map;
$scope.dynMarkers = [];
$scope.markers.forEach(function (marker) {
var latLng = new google.maps.LatLng(marker.latitude, marker.longitude);
var contentString = 'is an example string'
var infoWindow = new (google.maps.InfoWindow)({ content: contentString });
var dynMarker = new google.maps.Marker({ position: latLng });
$scope.dynMarkers.push(dynMarker);
google.maps.event.addListener(dynMarker, 'click', function () {
infoWindow.open(map,dynMarker);
});
});
var mcOptions = { imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m' };
$scope.markerClusterer = new MarkerClusterer(map, $scope.dynMarkers, mcOptions)
});
$scope.markers = [
{ id: 1, name: 'Oslo', latitude: 59.923043, longitude: 10.752839 },
{ id: 2, name: 'Stockholm', latitude: 59.339025, longitude: 18.065818 },
{ id: 3, name: 'Copenhagen', latitude: 55.675507, longitude: 12.574227 },
{ id: 4, name: 'Berlin', latitude: 52.521248, longitude: 13.399038 },
{ id: 5, name: 'Paris', latitude: 48.856127, longitude: 2.346525 }
];
});
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<script src="https://googlemaps.github.io/js-marker-clusterer/src/markerclusterer.js"></script>
<div ng-app="mapApp" ng-controller="mapController">
<ng-map default-style="true" zoom="3" center="59.339025, 18.065818">
</ng-map>
</div>
I have a problem with the position of the markercluster's infoWindow. It doesn't show up at the marker position. Instead it is positioned on the upper left corner of the map. Here is my code:
<script type="text/javascript">
function initialize(cities) {
var mapOptions = {
center: new google.maps.LatLng(48.220, 15.199),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var markers=[];
var markerCluster = new MarkerClusterer(map, markers, {zoomOnClick: false});
//markerCluster should be always above the geocoder-->
geocoder = new google.maps.Geocoder();
for (var i = 0; i < cities.length; i++) {
var city = cities[i];
geocoder.geocode({'address': city.city+" Niederösterreich"}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
position=results[0].geometry.location;
var marker = new google.maps.Marker({
map: map,
position: position,
title: "Ort: "+city.city + "\nBeitrag: " + city.title +"\nRed.: "+ city.reporter +"\nDatum: "+ city.storydate,
});
// below code alway lies inside the loop
markers.push(marker);
markerCluster.addMarker(marker);
}
});
};
// Listen for a cluster to be clicked
google.maps.event.addListener(markerCluster, 'clusterclick', function(cluster) {
var markers = markerCluster.getMarkers();
var content = '';
for (var i = 0; i < markers.length; i++) {
var marker = markers[i];
content += marker.title;
content += ("<br>");
};
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
var infowindow = new google.maps.InfoWindow();
// infowindow.setPosition(this.markerCluster.getCenter());
// infowindow.setPosition(latLng);
infowindow.close();
infowindow.setContent(content);
infowindow.open(map, info);
google.maps.event.addListener(map, 'zoom_changed', function() { infowindow.close() });
});
}
</script>
Your MVCObject doesn't have any properties. According to the documentation, if you pass the optional anchor argument into the function .open, it must expose a LatLng position property, yours doesn't (as it doesn't have any properties, it can't expose any).
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.
The simplest solution is to not use the anchor argument, set the position of the infowindow directly.
google.maps.event.addListener(markerCluster, 'clusterclick', function (cluster) {
var markers = cluster.getMarkers();
var content = '';
for (var i = 0; i < markers.length; i++) {
var marker = markers[i];
content += marker.title;
content += ("<br>");
}
var infowindow = new google.maps.InfoWindow();
infowindow.setPosition(cluster.getCenter());
infowindow.setContent(content);
infowindow.open(map);
google.maps.event.addListener(map, 'zoom_changed', function () {
infowindow.close();
});
});
proof of concept fiddle
code snippet:
var geocoder;
var markers = [];
function initialize(cities) {
var mapOptions = {
center: new google.maps.LatLng(48.220, 15.199),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var markerCluster = new MarkerClusterer(map, markers, {
zoomOnClick: false,
imagePath: 'https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library#07f15d84/markerclustererplus/images/m'
});
//markerCluster should be always above the geocoder-->
geocoder = new google.maps.Geocoder();
for (var i = 0; i < cities.length; i++) {
var city = cities[i];
geocodeCity(city, markerCluster);
}
// Listen for a cluster to be clicked
google.maps.event.addListener(markerCluster, 'clusterclick', function(cluster) {
var markers = cluster.getMarkers();
var content = '';
for (var i = 0; i < markers.length; i++) {
var marker = markers[i];
content += marker.title;
content += ("<br>");
}
var infowindow = new google.maps.InfoWindow();
infowindow.setPosition(cluster.getCenter());
infowindow.close();
infowindow.setContent(content);
infowindow.open(map);
google.maps.event.addListener(map, 'zoom_changed', function() {
infowindow.close();
});
});
}
function geocodeCity(city, markerCluster) {
geocoder.geocode({
'address': city.city + " Niederösterreich"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
position = results[0].geometry.location;
var marker = new google.maps.Marker({
map: map,
position: position,
title: "Ort: " + city.city + "\nBeitrag: " + city.title + "\nRed.: " + city.reporter + "\nDatum: " + city.storydate
});
// below code alway lies inside the loop
markers.push(marker);
markerCluster.addMarker(marker);
} else {
document.getElementById('info').innerHTML += city.city + " status=" + status + "<br>";
}
});
}
google.maps.event.addDomListener(window, "load", function() {
initialize(cities);
});
var cities = [{
city: "Sankt Polten",
title: "title 0",
reporter: "reporter 0",
storydate: "November 25,2015 00:00:00"
}, {
city: "Wiener Neustadt",
title: "title 1",
reporter: "reporter 1",
storydate: "November 25, 2015 01:01:01"
}, {
city: "Baden",
title: "title 2",
reporter: "reporter 2",
storydate: "November 25,2015 02:02:02"
}, {
city: "Klosterneuburg",
title: "title 3",
reporter: "reporter 3",
storydate: "November 25, 2015 03:03:03"
}, {
city: "Krems",
title: "title 4",
reporter: "reporter 4",
storydate: "November 25,2015 04:04:04"
}, {
city: "Amstetten",
title: "title 5",
reporter: "reporter 5",
storydate: "November 25, 2015 05:05:05"
}, {
city: "Modling",
title: "title 6",
reporter: "reporter 6",
storydate: "November 25,2015 06:06:06"
}, {
city: "Traiskirchen",
title: "title 7",
reporter: "reporter 7",
storydate: "November 25, 2015 07:07:07"
}, {
city: "Schwechat",
title: "title 8",
reporter: "reporter 8",
storydate: "November 25,2015 08:08:08"
}, {
city: "Ternitz",
title: "title 9",
reporter: "reporter 9",
storydate: "November 25, 2015 09:09:09"
}, {
city: "Stockerau",
title: "title 10",
reporter: "reporter 10",
storydate: "November 25,2015 10:10:10"
}];
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library#07f15d84/markerclustererplus/src/markerclusterer.js"></script>
<div id="info"></div>
<div id="map"></div>
OBJECT
var malls = [{
id: 0,
name: 'Leclerc',
lastname: 'Paris,France',
address:'Boulevard Rahal El Meskini Casablanca Maroc',
]
},
{
/*Malls B*/
id: 1,
name: 'Carefour',
lastname: 'Toulouse,France',
address:'Angle Zaid Ou Hmad Rue Sidi Belyout, Casablanca Maroc', }, ];
MY CONTROLLER
var address = "";//document.getElementById('address').value;
var id_mall ="";
var malls = Malls.all();
for (var i = 0; i < malls.length; i++) {
mall = malls[i];
addMarker(mall);}
function addMarker(address) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 14,
center: latlng
}
id = mall.id;
address = mall.address;
console.debug(address);
map = new google.maps.Map(document.getElementById('map'), mapOptions);
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,
title: 'shopping center',
position: results[0].geometry.location,
url:'#/tab/malls/'+id
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href=marker.url;
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
//google.maps.event.addDomListener(window, 'load', initialize);
}
I have 2 markers, and when I click on a marker , I receive :tab/malls/1 and the other the same thing normally have to be /tab/malls/0 and tab/malls/1 ,
I did not find the solution.
Please need help
Your object code appears malformed: there is an unmatched ] character on line 8. Try deleting this character and running it.
Currently, I am displaying 500-600 Markers on Google map, with their names as tooltip. Now,
I need to display the tool-tip of all overlapping markers as comma-separated i.e. Marker1, Marker2, Marker3 etc. if Marker1, Marker2, Marker3 are overlapped on map.
I found many other different examples on google map at internet especially at GeoCodeZip, but not of my requirement.
if this requirement is once filled, Am afraid of performance issues on zoom changed events, as tooltip needed to be updated (if overlapping is changed).
Update1 : I have already show Overlapping Marker spiderfier to client but not acceptable.
Does anyone have right path or working example ?
Thanks
-Anil
The core of this is to find the pixel distance between LatLngs. Then before adding each marker check the pixel distance between it and any existing markers. If there is another marker nearby add to the title otherwise create a new marker. jsFiddle
function init() {
var mapOptions = {
center: new google.maps.LatLng(0, -0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
// to get the pixel position from the latlng
// https://stackoverflow.com/questions/1538681/how-to-call-fromlatlngtodivpixel-in-google-maps-api-v3
var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
google.maps.event.addListenerOnce(map, 'idle', function() {
if (overlay.getProjection()) {
var points = [
{ latlng: new google.maps.LatLng(40, -100), title: '1' },
{ latlng: new google.maps.LatLng(40.125, -100.125), title: '2' },
{ latlng: new google.maps.LatLng(40.25, -100.25), title: '3' },
{ latlng: new google.maps.LatLng(40.5, -100.5), title: '4' },
{ latlng: new google.maps.LatLng(40.75, -100.75), title: '5' },
{ latlng: new google.maps.LatLng(41, -101), title: '6' },
{ latlng: new google.maps.LatLng(35, -95), title: '7' },
{ latlng: new google.maps.LatLng(45, 105), title: '8' },
{ latlng: new google.maps.LatLng(25, -115), title: '9' },
{ latlng: new google.maps.LatLng(55, -85), title: '10' },
{ latlng: new google.maps.LatLng(30, -34), title: '11' }
];
// for each point
var markers = [];
points.forEach(function (point) {
var nearby = false;
var pointPixelPosition = overlay.getProjection().fromLatLngToContainerPixel(point.latlng);
markers.forEach(function(marker) {
var markerPixelPosition = overlay.getProjection().fromLatLngToContainerPixel(marker.getPosition());
// check for marker 'near by'
if (Math.abs(pointPixelPosition.x - markerPixelPosition.x) < 10 || Math.abs(pointPixelPosition.y - markerPixelPosition.y) < 10) {
nearby = true;
marker.setTitle(marker.getTitle() + ', ' + point.title);
}
});
// create new marker
if (!nearby) {
markers.push(new google.maps.Marker({ map: map, position: point.latlng, title: point.title }));
}
});
}
map.setCenter(new google.maps.LatLng(39.8282, -98.5795));
});
}