google map api draggable route again come to original position - javascript

In google map api when i drag a route, route drags, but when i leave mouse click route goes to it's old position.
Can anyone tell me what's the reason behind this.
I can't show you all code, But here is some code:-
var rendererOptions = {
map: map,
suppressMarkers : true,
preserveViewpoint: true,
polylineOptions:{strokeColor:'blue',clickable:true},
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
and
directionsService.route(request, function(result, status) {
if(start!=end)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setOptions({ preserveViewport: true });
directionsDisplay.setDirections(result);
google.maps.event.addListener(directionsDisplay, 'directions_changed',function () {
});
}
}
});

Got it. way points has same coordinates when i drag.
Thank you for help

Related

Google markers not showing up

I want to use Google API to show route between A and B point and show all company's locations as marker. Showing route works well. But markers not displaying and showing no error.
Here is my code:
google.maps.event.addDomListener(window, "load", initMap);
function initMap() {
//create map
map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);
ContextMenu = document.getElementById("my-context-menu");
google.maps.event.addListener(map, "rightclick", function (ev) {
currentLatLng = ev.latLng;
console.log(ev.latLng);
ShowContextMenuGoolge(ContextMenu, ev);
/** this stop NOT stopping DOM 'context-menu' event from firing */
ev.stop();
});
google.maps.event.addListener(map, "click", function () {
HideContextMenuGoolge(ContextMenu);
});
//create a DirectionsService object to use the route method and get a result for our request
directionsService = new google.maps.DirectionsService();
//create a DirectionsRenderer object which we will use to display the route
directionsDisplay = new google.maps.DirectionsRenderer();
//bind the DirectionsRenderer to the map
directionsDisplay.setMap(map);
$.ajax({
type: "GET",
url: getAllMarkers,
success: function (res) {
createMarker(res);
},
err: function (err) {},
});
}
function createMarker(companies) {
// console.log(map);
companies.map((el) => {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(el.lat, el.lng),
map: map,
});
comMarkers.push(marker);
});
console.log(comMarkers);
}
This is result SS. Calculating route is works fine.
Thank for helping me.

How can i disable infowindow for origin and destination on Google map?

I am creating direction service on google map. Everything is working fine.
I want to disable infowindow of origin(A) and destination(B) points only not marker's. How can I hide it or remove it?
Check this attached image for more details
Here is code for setup google map. It is written in angular.
$scope.directionsService.route({
origin: {'placeId': $scope.originPlaceId},
destination: {'placeId': $scope.destinationPlaceId},
travelMode: defaultTravelMode
},
function (response, status) {
if (status === 'OK') {
$scope.directionsDisplay.setDirections(response);
$scope.path = new google.maps.Polyline({
path: response.routes[0].overview_path
});
// filter stores by path
$scope.filterStoresByDirectionPath($scope.path);
}
});
//function to design infowindow of marker
$scope.newMarker = function (opts) {
let marker = new google.maps.Marker(opts);
marker.travelTime = opts.travelTime;
marker.timeValue = opts.timeValue;
marker.url = opts.url;
$scope._on({
obj: marker,
event: 'click',
callback: function () {
let content = 'Marker content';
if ($scope.infoWindow) {
$scope.infoWindow.close();
}
$scope.infoWindow = new google.maps.InfoWindow({content: content});
$scope.infoWindow.open($scope.map, marker);
}
});

Google Maps API v.3 can't add marker when clicking a spot on the map

I'm using addEventListener to add new Marker to Google Maps using angular version 6.
I get everything needed but the actual Marker icon, it does not show on the map, why?
Here is a link to a working example on developers.google.com
https://developers.google.com/maps/documentation/javascript/info-windows-to-db
private isMapInitialized = false;
private map: any;
// Here everything statrs
ngOnInit() {
this.openMapPanel();
}
// Here I get the map and everything works great!
openMapPanel() {
setTimeout(() => {
if (!this.isMapInitialized) {
this.initMap();
this.isMapInitialized = true;
}
}, 300);
}
initMap() {
var california = {lat: 37.4419, lng: -122.1419};
this.map = new google.maps.Map(document.getElementById('map'), {
center: california,
zoom: 13
});
google.maps.event.addListener(this.map, 'click', function(event) {
this.placeNewMarker(event.latLng);
});
}
placeNewMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: this.map
});
});
}
do I miss something?
It was so simple.. all I needed to do is change that line of code.
google.maps.event.addListener(this.map, 'click', function(event) {
this.placeMarker(event.latLan);
}
to
google.maps.event.addListener(this.map, 'click', (event) => {
this.placeMarker(event.latLan);
});
and of course add the function
placeNewMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: this.map
});
});
I hope it will help someone someday :-)

Triggering Google Maps resize

I have no JavaScript or jQuery knowledge, I have no idea what to do with this Google Maps code.
I need to trigger this Google Maps resize code:
google.maps.event.trigger(map, 'resize');
The resize code above needs to be triggered after this waypoints is triggered below:
// Studio Page
jQuery('.studio-page').waypoint(function() {
jQuery('.kickass-studio').addClass( 'show animated bounceInLeft' );
jQuery('.location').addClass( 'show animated bounceInRight' );
jQuery('.geo-address').addClass( 'show animated bounceInDown' );
},
{
offset: '10%'
});
The above code is waypoints.js. My problem is that Google Maps breaks (you can only see the top left corner of the map). But from what I have found on Stack Overflow and other forums, this is due to the fact that the div is going from display: none to display: block after my waypoints plugin is done (adds class "show"). So I need to then trigger the Google Maps resize after waypoints is done adding those classes.
How would I go about doing this?
EDIT:
I have tried this:
// Studio Page
jQuery('.studio-page').waypoint(function() {
jQuery('.kickass-studio').addClass( 'show animated bounceInLeft' );
jQuery('.location').addClass( 'show animated bounceInRight' );
jQuery('.geo-address').addClass( 'show animated bounceInDown' );
var currCenter = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(currCenter);
},
{
offset: '10%'
});
But putting the above resize trigger there throws the Google Maps off my long and lat center point where my marker is?
EDIT:
Here is my maps script:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var latlng = new google.maps.LatLng(-33.8333406,18.6470022);
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map"),myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"Get Directions"
});
}
function calcRoute() {
var start = document.getElementById("routeStart").value;
var end = "-33.8333406,18.6470022";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
if (status == 'ZERO_RESULTS') {
alert('No route could be found between the origin and destination.');
} else if (status == 'UNKNOWN_ERROR') {
alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
} else if (status == 'REQUEST_DENIED') {
alert('This webpage is not allowed to use the directions service.');
} else if (status == 'OVER_QUERY_LIMIT') {
alert('The webpage has gone over the requests limit in too short a period of time.');
} else if (status == 'NOT_FOUND') {
alert('At least one of the origin, destination, or waypoints could not be geocoded.');
} else if (status == 'INVALID_REQUEST') {
alert('The DirectionsRequest provided was invalid.');
} else {
alert("There was an unknown error in your request. Requeststatus: \n\n"+status);
}
}
});
}
Use these lines for centering your google map after resizing:
var currCenter = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(currCenter);

Geocode Javascript problem

I wonder whether someone may be able to help me please.
Because of loading issues, I've moved the map options code to my HTML form, rather than it being in a separate Javascript file.
The problem is that I now can't get the Geocode functionality to work. I've added my code below. I'm sure it must be something simple, but I'm a little perplexed by this. I just wondered whether it would be at all possible please that someone could let me know where I've gone wrong.
Many thanks
function geocode() {
// This is defining the global variables
var geocoder, marker;
// This is making the link with the 'Search For Location' HTML form
var form = document.getElementById('searchforlocationform');
// This is catching the forms submit event
form.onsubmit = function() {
// This is getting the Address from the HTML forms 'Address' text box
var address = document.getElementById('inputaddress').value;
// This is making the Geocoder call
getCoordinates(address);
// This is preventing the form from doing a page submit
return false;
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
},
function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
//New Code
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
//Changed 'address' to 'returnedaddress'
function updateMarkerAddress(str) {
document.getElementById('returnedaddress').value= str;
}
// This creates the function that will return the coordinates for the address
function getCoordinates(address) {
// This checks to see if there is already a geocoded object. If not, it creates one
if(!geocoder){geocoder = new google.maps.Geocoder();}
// This is creating a GeocoderRequest object
var geocoderRequest = {address: address}
// This is making the Geocode request
geocoder.geocode(geocoderRequest, function(results, status) {
// Check if status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
// Center the map on the returned location
map.setCenter(results[0].geometry.location);
// Check to see if we've already got a Marker object
if (!marker) {
map.setZoom(16);
marker = new google.maps.Marker({
map: map, draggable:true
});
}
// Setting the position of the marker to the returned location
marker.setPosition(results[0].geometry.location);
// Add dragging event listeners.
google.maps.event.addListener(marker, function() {
updateMarkerAddress;
});
//This fills out the 'Latitude' and 'Longitude' text boxes on the HTML form
document.getElementById('osgb36lat').value= results[0].geometry.location.lat();
document.getElementById('osgb36lon').value= results[0].geometry.location.lng();
//This allows the marker to be draggable and tells the 'Latitude' and 'Longitude' text boxes on the HTML form to update with the new co-ordinates as the marker is dragged
google.maps.event.addListener(marker,'dragend',
function() {
updateMarkerStatus;
geocodePosition(marker.getPosition());
document.getElementById('osgb36lat').value = marker.position.lat();
document.getElementById('osgb36lon').value = marker.position.lng();
});
// Update current position info.
latLng = [marker.position.lat(), marker.position.lng()].join(', ');
geocodePosition(marker.getPosition());
var point = marker.getPosition();
map.panTo(point);
}
}
)
}
<script type="text/javascript">
(function() {
window.onload = function(){
var latlng = new google.maps.LatLng(54.312195845815246,-4.45948481875007);
var options = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_LEFT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
}
};
var map = new google.maps.Map(document.getElementById('map'), options);
}
})();
</script>
You seen to be trying to call updateMarkerAddress with updateMarkerAddress; and updateMarkerStatus with updateMarkerStatus;, here you are missing (/*some param*/).
What are the loading issues? Maybe if you show your html someone could help with that too.

Categories