Adding info boxes to Google Directions - javascript

I'm having trouble adding click-able info boxes to my google map Directions.
I can get this to work within the initialize function, but I need to get this to work when I add the extra markers via my xml file. See full code below.
Thanks for any help..
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var stepDisplay;
var map;
var markersArray;
var markers = [];
var infowindow;
function initialize() {
var latlng = new google.maps.LatLng( <? echo $lat; ?> , <? echo $lon; ?> );
var rendererOptions = {
draggable: true
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
//ADD LIST
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
function calcRoute() {
var travelMode = 'DRIVING';
var start = $("#routeStart").val();
var via = $("#routeVia2").val();
var end = $("#routeVia").val();
var waypoints = [];
if (via != '') {
waypoints.push({
location: via,
stopover: true
});
}
var request = {
origin: start,
destination: end,
waypoints: waypoints,
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: google.maps.DirectionsTravelMode[travelMode]
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var myRoute = response.routes[0];
var txtDir = '';
for (var i = 0; i < myRoute.legs[0].steps.length; i++) {
txtDir += myRoute.legs[0].steps[i].path + "";
}
var strLAT = "" + txtDir;
//---------------------------------------------------------
//SEND DATA TO URL
var DATET = $("#DATET").val();
var TIMET = $("#TIMET").val();
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("POST", 'MYPHPFILE', true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("LATLON=" + strLAT + "&getURL=" + end + "&TIMET=" + TIMET + "&DATET=" + DATET);
//-------------------------------------------------------
//RETURN DATA FOR PLACE MARKERS
var getURL = "MYXMLFILE" + end + ".xml";
jQuery.get(getURL, function(data) {
jQuery(data).find("marker").each(function() {
var eachMarker = jQuery(this);
var markerCoords = new google.maps.LatLng(
parseFloat(eachMarker.find("Lat").text()),
parseFloat(eachMarker.find("Lng").text())
);
var header = eachMarker.find("title").text();
var content = eachMarker.find("Content").text();
var wxicon = eachMarker.find("icon").text();
//--------------------------------------------------------------------------
//ADD INFO BOXES
var contentString = "HELLO WORLD";
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
//--------------------------------------------------------------------------
marker = new google.maps.Marker({
position: markerCoords,
icon: wxicon,
map: map,
animation: google.maps.Animation.DROP,
title: header,
});
});
});
//--------------------------------------------------------------------------
} else {
//ERROR MESSAGES
if (status == 'ZERO_RESULTS') {
alert('No route could be found between the origin and destination.');
} else if (status == 'INVALID_REQUEST') {
alert('The DirectionsRequest provided was invalid.');
} else {
alert("There was an unknown error in your request. Requeststatus: nn" + status);
}
}
});
}

Fixed, I changed marker to this, see below. Answer at http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/
//ADD INFO BOX
var contentString = "HELLO WORLD";
var infowindow = new google.maps.InfoWindow({
content: htmls,
});
//--------------------------------------------------------------------------
marker = new google.maps.Marker({
position: markerCoords,
icon: wxicon,
map: map,
animation: google.maps.Animation.DROP,
title: header,
html: htmls,
});
var contentString = "HELLO WORLD";
var infowindow = new google.maps.InfoWindow({
content: htmls,
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
});
});

Related

Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api

doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
script(src='/javascripts/jquery.min.js')
script(src='http://maps.google.com/maps/api/js?key=AIzaSyD6MCxtDJOnbE1T6Y09k8Uca1rXHTQ3Bqg&v=3.exp&sensor=true&libraries=place‌​s')
script(src='/javascripts/global.js')
h1= title
#loading
p Loading your location
br
#map
input#my-address(type='text')
button#getCords(onclick='codeAddress();') getLat&Long
I write above code in jade template for display the map i.e 'index.jade' and
following file i.e 'global.js' is script file
//Calling the locateme function when the document finishes loading
$(document).ready(function() {
locateMe();
});
//Function to locate the user
var locateMe = function(){
var map_element= $('#map');
if (navigator.geolocation) {
var position= navigator.geolocation.getCurrentPosition(loadMap);
} else {
map_element.innerHTML = "Geolocation is not supported by this browser.";
}
};
//Lets load the mop using the position
var loadMap = function(position) {
var loading= $('#loading');
var latitude=position.coords.latitude;
var longitude=position.coords.longitude;
var myLatlng = new google.maps.LatLng(latitude, longitude);
//Initializing the options for the map
var myOptions = {
center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
//Creating the map in teh DOM
var map_element=document.getElementById("map");
var map = new google.maps.Map(map_element,myOptions);
//Adding markers to it
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'You are here'
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow({
content: "<h2>You are here:</h2>",
//Settingup the maxwidth
maxWidth: 300
});
//Event listener to trigger the marker content
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);});
};
//get lat and log
function codeAddress() {
alert('inside')
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var map = new google.maps.Map(document.getElementById("my-address"),{
center:pyrmont,
zoom:15
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow();
alert(infowindow);
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, 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() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
};
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api
You are doing Place Search which doesnt return all of the fields that you are using:
http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_responses
In order to get the address, website, etc, you'll also need to call place.getDetails(), passing the Place's reference.
Below is a sample code snippet how to get Places details:
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
infowindow.open(map, this);
});
});
}

Markers not showing in Google Maps API

I have just loaded the following code into my webpage and after many hours of troubleshooting, I can't get the Markers to show up?
I have confirmed that the parsing php file is working.
Javascript:
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
var customIcons = {
accom: {
icon: 'images/google_map_icon_green.png'
},
food: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(
<?php if ($_COOKIE[company] == 'ch') { echo $ch[hls_lat].", ".$ch[hls_long]; } elseif ($_COOKIE[company] == 'shc') { echo $shc[hls_lat].", ".$shc[hls_long]; } elseif ($_COOKIE[company] == 'lmh') { echo $lmh[hls_lat].", ".$lmh[hls_long]; }?>),
zoom: 12,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infoWindow = new google.maps.InfoWindow;
downloadUrl("required/xml_parse.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var icao = markers[i].getAttribute("icao");
var type = markers[i].getAttribute("type");
var elev = markers[i].getAttribute("elev");
var conname = markers[i].getAttribute("contactname");
var connum = markers[i].getAttribute("contactnum");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> - " + icao + "<br/>" + conname + " - " + connum;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
SetMap: map_canvas,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map_canvas, infoWindow, html);
}
});
function bindInfoWindow(marker, map_canvas, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url,callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
HTML:
<br />
<div class="inner-article-header"><h2>Map of Locations</h2></div>
<div id="map_canvas" style="height:565px; width:754px; margin:2px;"></div>
</div>
This is incorrect:
SetMap: map_canvas,
Should be (see MarkerOptions in the documentation):
map: map,
corrected marker constructor:
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
Add the parsing of the XML into the initialize function, so map is valid when you add the markers:
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(0,0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(mapCanvas, mapOptions);
downloadUrl("example.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var icao = markers[i].getAttribute("icao");
var type = markers[i].getAttribute("type");
var elev = markers[i].getAttribute("elev");
var conname = markers[i].getAttribute("contactname");
var connum = markers[i].getAttribute("contactnum");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> - " + icao + "<br/>" + conname + " - " + connum;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
working example (using one of my existing xml files, since you didn't provide any example data)
You have additional problems with the call to bindInfoWindow and its definition (map_canvas, should be map)

Google Directions to wrong marker

I have a set of markers, and when clicked on a marker there is a button that gets directions. The problem is that it only gives directions to the last loaded marker from the xml, not to each marker individually. Here is my code, maybe someone can tell what I'm doing wrong. Thank you.
UPDATE: WORKING CODE, QUESTION ANSWERED
var map;
var point;
var directionsDisplay;
var directionsService;
var marker;
var myLatLng;
var marklat;
var marklong;
var markers;
var DirLat;
var DirLng;
function loadGoogleMap(){
// load google map
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=MyMap';
document.body.appendChild(script);
}
var map = ''
function MyMap(){
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
var im = //user location icon
var CustomMarker = //marker icon location
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(locate, noPos());
} else {
noPos();
}
function locate(position){
myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 12,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
panControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT},
zoomControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT }
}
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var userMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: im
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("phps/xmltest.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var nam = markers[i].getAttribute("name");
var name = nam.replace('=', '\'');
var address = markers[i].getAttribute("address");
var dt1 = markers[i].getAttribute("date1");
var dt2 = markers[i].getAttribute("date2");
var dt3 = markers[i].getAttribute("date3");
var tm1 = markers[i].getAttribute("time1");
var tm2 = markers[i].getAttribute("time2");
var tm3 = markers[i].getAttribute("time3");
var pid = markers[i].getAttribute("PID");
var DirLat = markers[i].getAttribute("lat");
var DirLng = markers[i].getAttribute("lng");
var d = Math.round(Math.random()*1679735965724*236896135089834);
var raw = pid * d;
//move up the creation of point
point = new google.maps.LatLng(
DirLat,
DirLng);
marker = new google.maps.Marker({
map: map,
position: point,
icon: CustomMarker,
id: raw,
id2: d
});
var content = "<button onclick='getDir();'>Get Directions</button>";
var jshtml = "<button onclick='raw();'>More Info</button>"; //an href function that redirects
var html = "<b>" + name + " " + content+ ' ' + jshtml+ "</b> <br/>" + "Date of Yard Sale: " + dt1 + ' ' + tm1 + ' ' + dt2 + ' ' + tm2 + ' ' + dt3 + ' ' + tm3;
bindInfoWindow(marker, map, infoWindow, html);
}
});
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker, html);
center: position;
document.getElementById('iLat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('iLng').value = marker.getPosition().lng().toFixed(6);
document.getElementById('iRaw1').value = marker.id;
document.getElementById('iRaw2').value = marker.id2;
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send();
}
function doNothing() {}
}
function noPos(error){
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(41.850033, -87.6500523),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
streetViewControl: false,
mapTypeControl: false,
panControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT},
zoomControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT }
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phps/xmltest.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var nam = markers[i].getAttribute("name");
var name = nam.replace('=', '\'');
var address = markers[i].getAttribute("address");
var dt1 = markers[i].getAttribute("date1");
var dt2 = markers[i].getAttribute("date2");
var dt3 = markers[i].getAttribute("date3");
var tm1 = markers[i].getAttribute("time1");
var tm2 = markers[i].getAttribute("time2");
var tm3 = markers[i].getAttribute("time3");
var pid = markers[i].getAttribute("PID");
var d = Math.round(Math.random()*1679735965724*236896135089834);
var raw = pid * d;
var jshtml = "<button onclick='raw();'>More Info</button>";;
var html = "<b>" + name + ' ' + jshtml + "</b>" + "<br>" + "Date of Yard Sale: " + dt1 + ' ' + tm1 + ' ' + dt2 + ' ' + tm2 + ' ' + dt3 + ' ' + tm3;
point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
marker = new google.maps.Marker({
map: map,
position: point,
icon: CustomMarker,
id: raw,
id2: d
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker, html);
position = marker.position;
center: position;
document.getElementById('iRaw1').value = marker.id;
document.getElementById('iRaw2').value = marker.id2;
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
}
}
function getDir(){
directionsDisplay.setMap(map);
var start = myLatLng;
//LatLng created based on the passed arguments
var end = point;
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);
}
});
}
I globally defined every variable necessary for directions:
var map;
var point;
var directionsDisplay;
var directionsService;
var marker;
var myLatLng;
var marklat;
var marklong;
var markers;
var DirLat;
var DirLng;
created a button for the function, and set in content which is visible in the infowindow:
var content = "<button onclick='getDir();'>Get Directions</button>";
Next I created hidden input fields in the map page, and assigned values of Latitude and Longitude of the markers that are clicked.
document.getElementById('iLat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('iLng').value = marker.getPosition().lng().toFixed(6);
The directions function getDir pulls these values for the destination, myLatLng is the current location of the user:
function getDir(){
directionsDisplay.setMap(map);
var start = myLatLng;
var LatDir = document.getElementById('iLat').value;
var LngDir = document.getElementById('iLng').value;
var end = new google.maps.LatLng(LatDir,LngDir);
var request = {
origin:myLatLng,
destination:new google.maps.LatLng(LatDir,LngDir),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
For the full code, see the updated question's code.

google maps event.addListener with xml

I am working on a dealerlocator with google maps. The problem is that when I click on a icon the infowindow opens the wrong window. I use a xml import. Everything is going well until the infowindow.
see website https://www.turbho.com/dealerview.php
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2maN7CjzWtwI6yuHj8lX078NzV0Ywkg0&sensor=false"></script>
{literal}
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Try HTML5 geolocation
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,
panControl: true,
zoomControl: true,
scaleControl: true,
content: 'U bent nu hier.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesnt support Geolocation
handleNoGeolocation(false);
}
var image = 'https://turbho.com/img/logoturbhogooglesmall.png';
// Change this depending on the name of your PHP file
downloadUrl("xml/datacomplete.xml", function (data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var zipcode = markers[i].getAttribute("zipcode");
var town = markers[i].getAttribute("town");
var anchor = markers[i].getAttribute("anchor");
var website = markers[i].getAttribute("website");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<span style='font-size:12px;'><b>" +
name + "</b> <br />" +
address + "<br />" +
zipcode + " " + town + "<br /><br />" +
website + "<br /><br />" +
anchor + "</span>";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image
});
var infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function () {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
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);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
{/literal}
<div id="map-canvas"></div>
The problem is solved. I used a function see below and that worked for me.
function add_marker(latlng, title, box_html, image) {
//create the global instance of infoWindow
if (!window.infowindow) {
window.infowindow = new google.maps.InfoWindow();
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: title,
icon: image
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.close();
infowindow.setContent(box_html);
infowindow.open(map, this)
});
return marker;
}
Thanx for the help
Ruud

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

Categories

Resources