Google map geolocator polyline edit color - javascript

site app which takes the user from it's current position and gives destination details to a specific point. And I have two problems. First I cannot figure out how I change the polyline color between the two points. The default is blue but I cannot seem to override it.
Also how do I get rid of the markers once the destination has been generated?
Where do I put this snippet in the code below for it to work?
var polylineOptions = {
strokeColor:"#FF0000",
strokeOpacity: 1,
strokeWeight: 2,
zIndex: 5
}
And heres the rest of the google map js.
var directionsService = new google.maps.DirectionsService(),
directionsDisplay = new google.maps.DirectionsRenderer(),
createMap = function (start) {
var travel = {
origin: (start.coords) ? new google.maps.LatLng(start.lat, start.lng) : start.address,
destination: customPosition,
travelMode: google.maps.DirectionsTravelMode.DRIVING
// Exchanging DRIVING to WALKING above can prove quite amusing :-)
},
map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("map-directions"));
directionsService.route(travel, function (result, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
var marker = new google.maps.Marker({
position: customPosition,
map: map,
clickable: false,
icon: 'images/minilogo.png',
animation: google.maps.Animation.DROP,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
});
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
// Success!
enableHighAccuracy: true,
$("#map-directions").show();
$("#geo").each(function () {
$(this).animate({
opacity: 0.5
}, 1000);
$(this).unbind();
$(this).html("<a>Position funnen!</a>");
});
console.log("that worked like a charm");
createMap({
polylineOptions:{strokeColor:'red'},
suppressMarkers:true,
coords: true,
lat: position.coords.latitude,
lng: position.coords.longitude
});
}, function errorCallback(error) {
// Gelocation fallback: Defaults to Stockholm, Sweden
console.log("Something went wrong, fallback initalized");
$("#geo").html("<a>Kunde inte hitta din position - pröva igen</a>");
$("#map-directions").hide();
$("#map-directions").unbind();
createMap({
coords: true,
address: customPosition,
zoom: 15
});
}, {
maximumAge: Infinity,
timeout: 10000
});
} else {
// No geolocation fallback: Defaults to Lisbon, Portugal
$('#geo').html('<p>Old browser, cannot run function</p>');
$("#map-directions").hide();
createMap({
coords: true,
address: customPosition
});
} //else
Thanks a lot!

You have to set them for DirectionsRenderer object:
directionsDisplay = new google.maps.DirectionsRenderer(),
Like
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: polylineOptions
}),
Or call
directionsDisplay.setOptions({
polylineOptions: polylineOptions
});

Related

Google Maps Infowindow issue after Geocode adaptation

I switched my code from the lat-lang system to the geocode API in order to resolve addresses, but unfortunately, the Google Maps Infowindows don't work properly. Only a few of them are displayed, with wrong information.
Here there is my code.
<script type="text/javascript">
if(document.getElementById("{idMap}")) {
let geocoder;
let map;
let locations = [
[ "Location 1" , "Via Pavia 57, 80021" ] ,
[ "Location 2" , "Via Palermo 24, 80021" ] ,
[ "Location 3" , "Via Milano 15, 80021" ] ,
];
function initializeMap() {
geocoder = new google.maps.Geocoder();
let infowindow = new google.maps.InfoWindow();
let bounds = new google.maps.LatLngBounds();
let mapSettings = {
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
fullscreenControl: false,
};
map = new google.maps.Map(document.getElementById("{idMap}"), mapSettings);
for (i = 0; i < locations.length; i++) {
codeAddress(locations[i][1], i, bounds);
}
}
function codeAddress(address, index, bounds) {
geocoder.geocode({ address: address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
let latLng = {
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng(),
};
if (status == "OK") {
let marker = new google.maps.Marker({
position: latLng,
map: map,
icon: "https://maps.google.com/mapfiles/ms/icons/blue-dot.png",
});
bounds.extend(marker.position);
map.fitBounds(bounds);
map.panToBounds(bounds);
if(locations[0][index] && locations[0][index].length > 0) {
let infowindow = new google.maps.InfoWindow({
content: locations[0][index],
});
marker.addListener("click", function () {
infowindow.open(map, marker);
});
}
} else {
console.log(
"Geocode was not successful for the following reason: " + status
);
}
}
});
}
window.initMap = null;
window.initMap = initializeMap();
}
</script>
All the markers are correctly positioned, the issue is only related to the infoWindow.
I fixed the issue, passing the id from the marker to the location array, in this way it works:
let infowindow = new google.maps.InfoWindow({
content: locations[marker.id][1],
});

google map is rendered with multiple rounded tiles

map is devided into 3x3 tiles
I want to remove all the spaces and rounded corners so the map looks as if it is one full map without any divisions into tiles, maybe there is some kind of map tile atribute that I can modify to make it look like a normal map, below is my code
function initMap() {
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(50.8429, -0.1313),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "A",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "B",
map: map
});
google.maps.event.trigger(map, 'resize');
// get route from A to B
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 {
swal("не удалось загрузить карту");
}
});
}
initMap();
the tiles of the map are effected by img styling, I changed my css to bypass the map styling and it solved my issue

How to remove Google maps default pointers?

I need to customize a map to look like this :
I was managed to add my own pointer icons and change the direction style to dots - but the default pointers are still appears....
Here is my Fiddle
Here what I've done so far :
map = new google.maps.Map(document.getElementById('map-canvas'),
myOptions),
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
map: map,
icon:'https://drive.google.com/uc?id=0B3RD6FDNxXbdVXRhZHFnV2xaS1E',
}),
markerB = new google.maps.Marker({
position: pointB,
map: map,
icon:'https://drive.google.com/uc?id=0B3RD6FDNxXbdM3E5clBqWDY5MWM',
});
I also would like to know how can i add the kilometers sum as a tooltip that keeps it's position relative to the route - like in the picture, any help will appreciated.
O.k - i got most of the stuff done, here is the result.
function initMap() {
var lineSymbol = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#3da6f9',
fillOpacity: 1,
anchor: new google.maps.Point(0,0),
strokeWeight: 0,
strokeOutline:2,
scale: 0.2
};
var pointA = new google.maps.LatLng(51.7519, -1.2578),
pointB = new google.maps.LatLng(50.8429, -0.1313),
myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: '#426289',
strokeOpacity: 0.4,
strokeWeight: 5,
icons: [{
icon: lineSymbol,
offset: '0px',
repeat: '15px'
}]
},
suppressMarkers: true,
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
icon: 'https://drive.google.com/uc?id=0B3RD6FDNxXbdVXRhZHFnV2xaS1E',
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
icon: 'https://drive.google.com/uc?id=0B3RD6FDNxXbdM3E5clBqWDY5MWM',
map: map
});
// get route from A to B
calculateAndDisplayRoute(directionsService, directionsDisplay, pointA,
pointB);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay,
pointA, pointB) {
directionsService.route({
origin: pointA,
destination: pointB,
avoidTolls: true,
avoidHighways: false,
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);
}
});
}
initMap();
And here is the Result

First create marker on google maps take too much time

I'm using the google maps API V3 in javascript and Vue.js for my application and i have found a strange bug, when i click the first time to put a marker on the map, the web app froze during 1-3seconds. Here is my code:
var vueMap = new Vue({
el: '#map-canvas',
data: {
infowindow: new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
}),
marker: null
},
ready:function(){
this.initialize();
},
methods: {
createMarker: function (latlng, name, html, point1, map) {
var distanceKm = google.maps.geometry.spherical.computeDistanceBetween(point1, latlng);
distanceKm = distanceKm/1000;
distanceKm = distanceKm.toFixed(2);
var contentString = "Distance en KM ---- " + distanceKm + '<br/>Score de 123';
// HERE IS WHERE THE FROZE HAPPEN
this.marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
// TODO onclick
google.maps.event.addListener(this.marker, 'click', function() {
this.infowindow.setContent(contentString);
this.infowindow.open(map,this.marker);
}.bind(this));
google.maps.event.trigger(this.marker, 'click');
return this.marker;
},
initialize: function () {
var styles = [/*some style*/];
var styledMap = new google.maps.StyledMapType(styles,
{name: "Styled Map"});
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(48.815145,2.244830),
new google.maps.LatLng(48.902137, 2.417864)
);
var point1 = new google.maps.LatLng(48.858230, 2.372566);
var center = bounds.getCenter();
var x = bounds.contains(center);
var mapOptions = {
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
},
center: center,
zoom: 1,
minZoom: 13,
streetViewControl: false,
mapTypeControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_CENTER
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
}
};
console.log(document.getElementById('map-canvas'));
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var lastValidCenter = map.getCenter();
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
google.maps.event.addListener(map, 'center_changed', function() {
if (bounds.contains(map.getCenter())) {
// still within valid bounds, so save the last valid position
lastValidCenter = map.getCenter();
return;
}
// not valid anymore => return to last valid position
map.panTo(lastValidCenter);
});
google.maps.event.addListener(map, 'click', function(event) {
//call function to create marker
if (this.marker != null) {
this.marker.setMap(null);
this.marker = null;
}
this.marker = vueMap.createMarker(event.latLng, "name", "<b>Location</b><br>"+event.latLng, point1, map);
}.bind(this));
}
}
});
module.exports = vueMap;
It's longer on Chrome than with Firefox and Safari...
Does someone knows why ? (Or have a clue about it ?)
Thanks in advance

How to make Google Maps V3 polyline snap to road from given points?

I try to make a polyline snap to road from given marker points. My problem is, that the same
code sometimes gives the good results, like in this image
and sometimes a bad result, like this:
Any ideas why this is hapenning? And also, is there a limitation for polyline snap to road?
My map ini code:
var myLatlng = new google.maps.LatLng(47.6557, 23.5833);
var mapOptions = {
zoom: 14,
minZoom: 13,
maxZoom: 19,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
overviewMapControl: false,
streetViewControl: false,
scaleControl: false,
mapTypeControl: false,
panControl: true,
panControlOptions:{
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_RIGHT
}
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
My polyline route snap code:
var polys = new google.maps.Polyline({
map: map,
strokeColor: "#5555FF"
});
myCoord = [
new google.maps.LatLng(47.663383463156144, 23.58100461977301),
new google.maps.LatLng(47.659221287827435, 23.586240291770082),
new google.maps.LatLng(47.65534785438211, 23.576713085349184),
new google.maps.LatLng(47.66020405359421, 23.572249889548402)
];
// BEGIN: Snap to road
var service = new google.maps.DirectionsService(),polys,snap_path=[];
polys.setMap(map);
placeMarker(myCoord[0], map);
for(j=0;j<myCoord.length-1;j++){
service.route({origin: myCoord[j],destination: myCoord[j+1],travelMode: google.maps.DirectionsTravelMode.DRIVING},function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
snap_path = snap_path.concat(result.routes[0].overview_path);
polys.setPath(snap_path);
}
});
}
If you just want directions with waypoints, you should just call the directionsService once with those waypoints, something like this (not tested):
var service = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var waypts = [];
for(j=1;j<myCoord.length-1;j++){
waypts.push({location: myCoord[j],
stopover: true});
}
var request = {
origin: myCoord[0],
destination: myCoord[myCoord.length-1],
waypoints: waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
service.route(request,function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
} else { alert("Directions request failed:" +status); }
});
Note: there is a maximum of 8 waypoints with the free API.

Categories

Resources