Route map are drawn improperly in google maps in javascript - javascript

I am developing a web application and integrated google maps with java script. markers are working fine with good latitude and longitude. the route map is not shown perfectly. when search users in a route map, not showing properly. it shows different routes. it didn't clear previous route. How can I clear previous route?
Route Map Screen shot
sample maps code:
var marker= [];
var geocoder;
var map;
var directionsDisplay,directionsService;
directionsDisplay = new google.maps.DirectionsRenderer({ draggable: false, suppressMarkers: true });
directionsService = new google.maps.DirectionsService();
var request = {
travelMode: google.maps.TravelMode.DRIVING
};
googleMapCoordinates(response);
function googleMapCoordinates(response) {
setMapOnAll(null);
marker = [];
directionsDisplay.setMap(null);
directionsDisplay.setPanel(null);
$("#map").show();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(17.7254567, 83.3097112),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
var i;
for (i = 0; i < response.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(response[i].latitude, response[i].longitude),
map:map,
label:response[i].count
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("Name :"+response[i].name);
infowindow.open(map, marker);
}
})(marker, i));
/******************Direction*********************************/
if (i == 0) request.origin = marker.getPosition();
else if (i == response.length - 1) request.destination = marker.getPosition();
else {
if (!request.waypoints) request.waypoints = [];
request.waypoints.push({
location: marker.getPosition(),
stopover: true
});
}
}
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
function setMapOnAll(map) {
console.log("Set map is to empty state ");
for (var i = 0; i < marker.length; i++) {
marker[i].setMap(map);
}
}

Related

Cannot drag marker properly in Google Map using JavaScript

I cannot drag marker of Google Map using JavaScript. Here is my code:
geocoder.geocode( { 'address': addrs}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#latitude').val(results[0].geometry.location.lat());
$('#longitude').val(results[0].geometry.location.lng());
var latitude=results[0].geometry.location.lat();
var longitude=results[0].geometry.location.lng();
var title=document.getElementById('googleMap').value;
var desc=title+","+address;
console.log(latitude,longitude);
var markers = [{"lat":latitude,"lng":longitude},{"title": title,"lat":latitude,"lng":longitude,"description":desc}];
// $window.addEventListener('load', onload, false);
// $window.onload = function () {
setTimeout(function(){
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.trigger(map, "resize");
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
google.maps.event.addListener(marker, 'dragend', function (event) {
var latdrag = this.getPosition().lat();
var longdrag= this.getPosition().lng();
console.log('latlong',latdrag,longdrag);
});
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
zoomChangeBoundsListener =
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(12);
}
});
setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);
},2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
Here my issue is I am able to drag the marker but while I am dragging the new marker is coming to droppable place and the first one is still there. Here I need that single marker will only drag to any place and no new marker will create.
You are creating two markers in the same place and dragging the top one.
var markers = [{"lat":latitude,"lng":longitude},{"title": title,"lat":latitude,"lng":longitude,"description":desc}];
creates an array with two elements and in the loop, two markers are created.

combine the DirectionsService and PlacesService in google map

How to combine the DirectionsService and PlacesService in google map. I will inspire on this path http://www.indiaproperty.com/godrej-palm-grove-in-poonamallee-chennai-pl4110632?fr=sres2 . I can't get the duration & distance of each location. I need to find each location distance and duration. I given the code below:
var map;
var infowindow;
var markersArray = [];
var pyrmont = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var places = [];
// var waypoints = [];
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 14,
zoomControl: false,
scaleControl: false,
scrollwheel: false,
disableDoubleClickZoom: true,
});
infowindow = new google.maps.InfoWindow();
//document.getElementById('directionsPanel').innerHTML='';
search_types();
}
function createMarker(place,icon) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
visible:true
});
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<b>Name:</b>"+place.name+"<br><b>Address:</b>"+place.vicinity+"<br><b>Reference:</b>"+place.reference+"<br><b>Rating:</b>"+place.rating+"<br><b>Id:</b>"+place.id);
infowindow.open(map, this);
});
}
var source="";
var dest='';
function search_types(latLng){
clearOverlays();
if(!latLng){
var latLng = pyrmont;
}
var placename = $('.nearby h3').attr("data-value")
var type = $('#valueStored').val();
var icon = "images/"+type+".png";
var request = {
location: latLng,
radius: 2000,
types: [type], //e.g. school, restaurant,bank,bar,city_hall,gym,night_club,park,zoo
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
$('.map-list').find('li').remove();
var service = new google.maps.places.PlacesService(map);
service.search(request, function(results, status) {
map.setZoom(14);
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
results[i].html_attributions='';
places[i] = results[i];
createMarker(results[i],icon);
$('.map-list').append('<li>'+results[i].name+'<div><span class="distance"></span> <span class="duration"></span></div></li>');
}
}
});
distanceCalc();
}
var latadd, longadd;
function distanceCalc(latLng){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var changeaddress;
var pyrmont1 = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var request = {
origin: pyrmont,
destination: pyrmont1,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var listed = $('.map-list li');
console.log(places[4]);
for (var i = 0; i < listed.length; i++) {
$('.distance').text(response.routes[0].legs[0].distance.value);
$('.duration').text(response.routes[0].legs[0].duration.value);
}
// Display the distance:
directionsDisplay.setDirections(response);
}
});
}
function showResult(result) {
latadd = result.geometry.location.lat();
longadd = result.geometry.location.lng();
}
// Deletes all markers in the array by removing references to them
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(false)
}
//markersArray.length = 0;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function clearMarkers(){
$('#show_btn').show();
$('#hide_btn').hide();
clearOverlays()
}
function showMarkers(){
$('#show_btn').hide();
$('#hide_btn').show();
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(true)
}
}
}

Issue with infoWindows with multiple markers and directionsDisplay variables in Google Maps API v3

I'm trying to display how distance and how minutes are between two markers in Google Maps API v3 and use these information to override the default infoWindow text that appears when the directionsService is fired, I think there is a asyncronous problem with calcRoute() and the infoWindows. This is an example code that reproduces the error.
<html>
<head>
<meta charset='utf-8'>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<script>
var directionsDisplay = new google.maps.DirectionsRenderer({ 'map': map });
var directionsService = new google.maps.DirectionsService();
var map;
function initMap(locations){
function calcRoute(latdest, lngdest) {
var start = new google.maps.LatLng(-23.571064, -46.645424);
var end = new google.maps.LatLng(latdest, lngdest)
var request = {origin:start,destination:end,travelMode: google.maps.TravelMode.DRIVING};
directionsService.route(request, function(result, status){
if (status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(result);
}
});
}
map = new google.maps.Map(document.getElementById('mapcanvas'), {zoom: 10,center: new google.maps.LatLng(-23.571064, -46.645424),mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
var infowindow = new google.maps.InfoWindow();
var marker, i;
var image = null;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
calcRoute(locations[i][1], locations[i][2]);
infowindow.setContent(directionsDisplay.directions.routes[0].legs[0].distance.text+" - "+directionsDisplay.directions.routes[0].legs[0].duration.text);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
</head>
<body onload='initMap([["Vila Noemia", -23.670237, -46.467286],["Osasco", -23.535465, -46.794234],["Guarulhos", -23.458911, -46.526912]]);'>
<div id="mapcanvas" style="width:100%;height:100%;">
</div>
</body>
Please note that if you click one marker, and then another, the second marker will show the desired result but that information belongs to the first marker... How can I force the order of execution to avoid the async?
Thanks in advance...
You want to open the infowindow in the DirectionsService callback function where the data is available.
(you may also want to suppress the existing markers from the directions service)
InfoWindow click listener:
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
calcRoute(locations[i][1], locations[i][2]);
infowindow.open(map, marker);
}
})(marker, i));
Updated calcRoute function:
function calcRoute(latdest, lngdest) {
var start = new google.maps.LatLng(-23.571064, -46.645424);
var end = new google.maps.LatLng(latdest, lngdest)
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
infowindow.setContent(directionsDisplay.directions.routes[0].legs[0].distance.text + " - " + directionsDisplay.directions.routes[0].legs[0].duration.text);
}
});
}
proof of concept fiddle
code snippet:
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true
});
var directionsService = new google.maps.DirectionsService();
var map;
var infowindow = new google.maps.InfoWindow();
function initMap(locations) {
function calcRoute(latdest, lngdest) {
var start = new google.maps.LatLng(-23.571064, -46.645424);
var end = new google.maps.LatLng(latdest, lngdest)
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
infowindow.setContent(directionsDisplay.directions.routes[0].legs[0].distance.text + " - " + directionsDisplay.directions.routes[0].legs[0].duration.text);
}
});
}
map = new google.maps.Map(document.getElementById('mapcanvas'), {
zoom: 10,
center: new google.maps.LatLng(-23.571064, -46.645424),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
var marker, i;
var image = null;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
calcRoute(locations[i][1], locations[i][2]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', function() {
initMap([
["Vila Noemia", -23.670237, -46.467286],
["Osasco", -23.535465, -46.794234],
["Guarulhos", -23.458911, -46.526912]
]);
});
html,
body,
#map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="mapcanvas" style="width:100%;height:100%;"></div>

removing last added marker from google maps v3

I'm working on a site that uses google maps v3, thanks to which you can navigate to a specific location
web site - http://dev.fama.net.pl/walendia/lokalizacja.html
type 'szczecin' on input that is at the top of the site and click submit - a marker will appear on the map, then type 'warszawa' - new marker will appear on the map but old one is still there, how to remove previous marker from the map
GOOGLE MAP CODE
var map;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();
var stepDisplay;
var markersArray = [];
var iconSize = new google.maps.Size(158,59);
var iconOrigin = new google.maps.Point(0,0);
var iconAnchor = new google.maps.Point(20,59);
function initialize(center, zoom) {
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
var mapOptions = {
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_RIGHT
}
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
geocoder.geocode({address: center}, function(results, status) {
map.setCenter(results[0].geometry.location);
});
}
function addMarker(location, icon) {
geocoder.geocode({address: location}, function(results, status) {
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon: icon
});
google.maps.event.addListener(marker);
markersArray.push(marker);
});
}
function addMarker2(position, icon) {
var location = new google.maps.LatLng(52.08901624831595, 20.854395031929016);
var icon = {
url: 'http://dev.fama.net.pl/walendia/img/markers/end.png',
size: iconSize,
origin: iconOrigin,
anchor: iconAnchor
}
marker = new google.maps.Marker({
position: location,
map: map,
icon: icon
});
markersArray.push(marker);
}
function calcRoute(start, end) {
var start = start;
var end = end;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var location = start;
var icon = {
url: 'http://dev.fama.net.pl/walendia/img/markers/start.png',
size: iconSize,
origin: iconOrigin,
anchor: iconAnchor
}
addMarker(location, icon);
addMarker2(location, icon);
directionsDisplay.setDirections(result);
}
});
}
// SET CENTER ON RESIZE
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
directionsDisplay.setMap(map);
});
$(document).ready(function() {
$('.form-box form').submit(function() {
var start = $(this).find('input[name="start"]').val();
var end = new google.maps.LatLng(52.08901624831595, 20.854395031929016);
directionsDisplay.setMap(map);
calcRoute(start, end);
return false;
});
});
HTML CODE
$(document).ready(function() {
initialize('Łączności 131, 05-552 Łazy, Polska', 10);
addMarker2(location);
});
Before adding second marker you need to delete marker from markersArray. Use the following function to delete markers from array.
function deleteMarkers() {
if (markersArray) {
for (i=0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
DEMO FIDDLE
NOTE: I just took some sample to remove and show markers when you click on buttons. Use those functions according to your requirement.

Google maps zoom level for country

I'm having a problem working out how to set the zoom level for different countries, I have managed to get the map working and displaying the country, just cannot seem to work out how to set the zoom level.
Any help would be appreciated.
Thanks
George
<script type="text/javascript">
var infowindow = null;
$(document).ready(function () { initialize(); });
function initialize() {
//var geocoder = new google.maps.Geocoder();
//geocoder.geocode({ 'address': address }, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
// map.fitBounds(results[0].geometry.viewport);
// }
//});
var centerMap = new google.maps.LatLng(#Html.Raw(#item.strLatLong));
var myOptions = {
zoom: 4, //<<-------How can I chnage this
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("WeatherMapLocation"), myOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
</script>
From the documentation on the Geocoder, there is a viewport and a bounds returned in the geocoder's response which can be used to center and zoom the map on the result.
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
working example

Categories

Resources