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

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

Related

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

Working with two google maps

Hi I need some help with the following:
I am trying to get two maps to display two different things.
My problem is, on the first map I would like to click on a link in the infowindow (see this) when I do click on that link, I would like that marker to display alone on the second map at its location.
here is my code. Thank you for any help.
$(document).ready(function() {
var map;
var service;
function initialise(location) {
console.log("location:" + location);
var currentLocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
var mapOption = {
center : currentLocation,
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOption);
var marker = new google.maps.Marker({
position : currentLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
//service = new google.maps.places.PlacesService(map);
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
function handleSearchResults(results, status) {
console.log(results)
}
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
});
var content = '<p>See this</p>'
var infowindow = new google.maps.InfoWindow({
content:('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + content)
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
var latitude = this.position.lat();
var longitude = this.position.lng();
console.log(this.position);
});
}
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
var input = $("#search").val();
var query = (input != '' )? input : "restaurant";
performSearch(query);
});
function performSearch(q){
var request ={
bounds: map.getBounds(),
query:String(q)
};
service.textSearch(request, callback);
}
}
function initializer() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
});
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
position : initialLocation,
map : map,
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
}
function initializer_2() {
var mapOption2 = {
center : new google.maps.LatLng(41.923, 12.513),
zoom : 14,
mapTypeId : google.maps.MapTypeId.ROADMAP,
};
var marker = new google.maps.Marker({
// need the position of marker
//position : currentLocation,
map : map,
});
map = new google.maps.Map(document.getElementById("map-canvas2"), mapOption2);
}
google.maps.event.addDomListener(window, 'load', initializer);
google.maps.event.addDomListener(window, 'load', initializer_2);
$(".getSearch").click(function () {
navigator.geolocation.getCurrentPosition(initialise);
});
});

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

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.

Categories

Resources