combine the DirectionsService and PlacesService in google map - javascript

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)
}
}
}

Related

Route map are drawn improperly in google maps in 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);
}
}

how to get center latitude and longitude in route between two location

I am using google map to find route between two location.i want to get center latitude and longitude of the route. can u please tell me how to get center of the route.i am using the below code for getting routes,Thanks in advance
var map;
var directionsDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var infoWindow;
var service;
var lat1 = 0;
var lng1;
function pre_initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var addressfrom = document.getElementById("from").value;
var addressto = document.getElementById("to").value;
var geocoder = new google.maps.Geocoder();
var coords = new google.maps.LatLng(0, 0);
alert(lat1);
coords = geocoder.geocode({ 'address': addressfrom }, function (results, status) {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
});
directionsService = new google.maps.DirectionsService();
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
// Instantiate an info window to hold step text.
infoWindow = new google.maps.InfoWindow();
stepDisplay = new google.maps.InfoWindow();
calcRoute();
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
radius: 100,
types: ['hospital', 'cafe', 'restaurant', 'food', 'bar'],
keyword: 'best view'
};
service = new google.maps.places.PlacesService(map);
//service.nearbySearch(request, callback);
service.radarSearch(request, callback);
//service.textSearch(request, callback);
}
function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon:
{
// Star
path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
fillColor: '#ff0000',
fillOpacity: 1,
scale: 1 / 4,
strokeColor: '#bd8d2c',
strokeWeight: 1
}
});
google.maps.event.addListener(marker, 'click', function () {
service.getDetails(place, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
});
});
}
function calcRoute() {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Now, clear the array itself.
markerArray = [];
var start = document.getElementById('from').value;
var end = document.getElementById('to').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response);
}
});
}
function showSteps(directionResult) {
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_point,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function () {
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
</script>
Refer to the code below:
self.adjustPosition = function () {
var lat = 0, lng = 0;
if (self.nearbyPlaces().length == 0) {
return false;
}
for (var i = 0; i < self.nearbyPlaces().length; i++) {
lat += self.nearbyPlaces()[i].latitude;
lng += self.nearbyPlaces()[i].longitude;
}
lat = lat / self.nearbyPlaces().length;
lng = lng / self.nearbyPlaces().length;
self.map.setCenter(new window.google.maps.LatLng(lat, lng));
};

How to edit default marker in google maps

Kindly check this map view: http://gmaps-samples-v3.googlecode.com/svn/trunk/map_language/map_lang.html
If you click on A or B, it will show location name in default marker. I wish to show some custom texts here. How can I do that?
My JavaScript code for this is:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var oldDirections = [];
var currentDirections = null;
//getting latitude and longitude from address
var latitude;
var longitude;
var geocoder = new google.maps.Geocoder();
var address = "Downtown Berkeley";
geocoder.geocode( { "address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
// do something with the geocoded result
//
latitude = results[0].geometry.location.lat()
longitude = results[0].geometry.location.lng()
alert(latitude )
}
});
//map initialize
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(-33.879,151.235),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//adding marker
var marker = new google.maps.Marker
(
{
position: new google.maps.LatLng(latitude , longitude),
map: map,
title: "Click me"
}
);
var infowindow = new google.maps.InfoWindow({
content: "Location info:<br/>Country Name:<br/>LatLng:"
});
google.maps.event.addListener(marker, "click", function () {
// Calling the open method of the infoWindow
infowindow.open(map, marker);
});
directionsDisplay = new google.maps.DirectionsRenderer({
"map": map,
"preserveViewport": true,
"draggable": true
});
directionsDisplay.setPanel(document.getElementById("directions_panel"));
google.maps.event.addListener(directionsDisplay, "directions_changed",
function() {
if (currentDirections) {
oldDirections.push(currentDirections);
}
currentDirections = directionsDisplay.getDirections();
});
calcRoute();
}
function calcRoute() {
var start = "El Cerrito del Norte";
var end = "Downtown Berkeley";
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);
}
});
}
You set that content in the createInfoWindow() method.

Google maps api and geolocation, Javascript and Html

Hey I'm new to the google maps api, and I have an embedded map, i'm using geolocation to get the users lat and long, and i'm then filling in the gaps in the maps api. The map, however doesn't work when I use the generated lat and long, but does work if i just type one in
Non-working code:
var map;
var infowindow;
function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
var latlon = new google.maps.LatLng( position.coords.latitude + "," + position.coords.longitude );
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
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
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Working code
var map;
var infowindow;
function initialize() {
var latlon = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
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
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Any help if appreciated :)
Replace your line:
var latlon = new google.maps.LatLng
(position.coords.latitude + "," + position.coords.longitude);
with
var latlon = new google.maps.LatLng
(position.coords.latitude, position.coords.longitude);
The problem is in concatenating two values into one where constructor expects two parameters.

Multiple markers in google map

I am scratching my head for google map integration please help me out.
I want multiple markers, but its taking only 11 markers not more than that.
Below is my code..
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1");</script>
<script type="text/javascript"> google.load("maps", "3", {other_params:"sensor=false"});</script>
<script type="text/javascript">
var geocoder;
var map, cloud;
var counter = 0;
var markers = [];
var locations = [];
locations[0] = "Charleston, SC";
locations[1] = "Tuscon, AZ";
locations[2] = "Phoenix, AZ";
locations[3] = "San Diego, CA";
locations[4] = "Los Angeles, CA";
locations[5] = "Aliso Viejo, CA";
locations[6] = "Laguna Beach, CA";
locations[7] = "Coto de Caza, CA";
locations[8] = "Philadelphia, PA";
locations[9] = "Ladera Ranch, CA";
locations[10] = "Thousand Oaks, CA";
var image = new google.maps.MarkerImage(
'../images/marker.png',
new google.maps.Size(28,54),
new google.maps.Point(0,0),
new google.maps.Point(14,54)
);
function init()
{
//alert(locations.length);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
for (var i = 0; i < locations.length; i++) {
makeMarker(locations[i]);
}
centerMap();
}
function centerMap()
{
map.setCenter(markers[markers.length-1].getPosition());
}
function makeMarker(location)
{
geocoder.geocode( { 'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: results[0].geometry.location
});
markers.push(marker);
alert(results[0].formatted_address);
var contentString = 'Content comes here';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close(map,marker);
});
}
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
You can see practical example in: http://projects.pronixtech.net/kindcampaign/kind-country/
I think the problem is in "geocoder.geocode".
Look this code, with LatLong it works.
var geocoder;
var map, cloud;
var counter = 0;
var markers = [];
var locations = [];
locations[0] = new google.maps.LatLng(10.32522, 10.07002);
locations[1] = new google.maps.LatLng(20.32522, 10.07002);
locations[2] = new google.maps.LatLng(30.32522, 10.07002);
locations[3] = new google.maps.LatLng(10.32522, 20.07002);
locations[4] = new google.maps.LatLng(20.32522, 20.07002);
locations[5] = new google.maps.LatLng(30.32522, 20.07002);
locations[6] = new google.maps.LatLng(10.32522, 30.07002);
locations[7] = new google.maps.LatLng(20.32522, 30.07002);
locations[8] = new google.maps.LatLng(30.32522, 30.07002);
locations[9] = new google.maps.LatLng(10.32522, 40.07002);
locations[10] = new google.maps.LatLng(20.32522, 40.07002);
locations[11] = new google.maps.LatLng(30.32522, 40.07002);
locations[12] = new google.maps.LatLng(10.32522, 50.07002);
locations[13] = new google.maps.LatLng(20.32522, 50.07002);
locations[14] = new google.maps.LatLng(30.32522, 50.07002);
locations[15] = new google.maps.LatLng(10.32522, 60.07002);
locations[16] = new google.maps.LatLng(20.32522, 60.07002);
locations[17] = new google.maps.LatLng(30.32522, 60.07002);
var image = new google.maps.MarkerImage(
'http://www.bookyourparis.com/images-site/beachflag.png',
new google.maps.Size(28,54),
new google.maps.Point(0,0),
new google.maps.Point(14,54)
);
function init()
{
//alert(locations.length);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
for (var i = 0; i < locations.length; i++) {
makeMarker(locations[i]);
}
centerMap();
}
function centerMap()
{
map.setCenter(markers[markers.length-1].getPosition());
}
function makeMarker(location)
{
//geocoder.geocode( { 'address': location}, function(results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
//map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: location//results[0].geometry.location
});
markers.push(marker);
//alert(results[0].formatted_address);
var contentString = 'Content comes here';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close(map,this);
});
//}
//});
}
google.maps.event.addDomListener(window, 'load', init);

Categories

Resources