How can i read custom field value and set as start & end in order to display google direction
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
In wordpress post i have 2 custom fields with start and destination value and i wish to read values and add to function calcroute() in order to display that route on google maps.
my entire code (below) display only centred view of Chicago
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('plecare_din').value;
var end = document.getElementById('destinatie').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
you have to trigger the calcRoute() somewhere
I have a working sample here in jsfiddle:
http://jsfiddle.net/th9kwzdr/1/
Related
I am working on google maps for quite some time, I am familiar with code and how it works, but unable to place the resize event properly that causes my map to render grey tiles on screen.
Please suggest me where exactly need to place the resize event
Here is my code :
bank.atmDetailsSuccess = function(response) {
bank.locate = response;
bank.getAtmStatus();
};
bank.getAtmStatus = function(results, status) {
var status = bank.locate.Status[0].Value0;
locate = bank.locate;
var map;
if (status == bank.constants.STATUS_ERROR) {
var message = locate.Error[0].Value0;
WL.simpledialog.show(message);
} else if (status == bank.constants.STATUS_SESSION_EXPIRED) {
WL.simpledialog.show("Session Expired!!");
} else if (status == bank.constants.STATUS_SUCCESS) {
map = bank.initializeAtm();
google.maps.event.addDomListener(window, 'load', initializeAtm);
google.maps.event.addDomListener(window, "resize", function() {
alert("In");
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
map.setZoom(10);
});
}
};
bank.initializeAtm = function(){
locate = bank.locate;
var firstlat = locate.Stmt[0].Value5;
var firstlong= locate.Stmt[0].Value6;
// var latlng = new google.maps.LatLng(latitude,longitude);
var image = {
//url: bank.constants.MARKER_PATH,
url: 'images/720x720/pin.png',
// This marker is 20 pixels wide by 32 pixels tall.
size: new google.maps.Size(32, 40),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
anchor: new google.maps.Point(0, 32)
};
var myOptions = {
zoom: 10,
center:new google.maps.LatLng(firstlat, firstlong),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map-canvas')[0], myOptions);
geocoder = new google.maps.Geocoder();
bank.currentposition();
$('#mapbranch').hide();
$('#map-canvas').show();
$('#atm').html("ATM near your current location");
$('#results').html("");
var directionsService = new google.maps.DirectionsService();
MVC.local.directService = directionsService;
directionsRenderer = new google.maps.DirectionsRenderer({
suppressMarkers: true} );
MVC.local.renderer = directionsRenderer;
var n;
for(n=0; n<locate.Stmt.length; n++)
{
var value = locate.Stmt[n];
name = value.Value0,value.Value1;
lat = value.Value5;
lon = value.Value6;
bank.getDistanceFromLatLonInKm(12.919336, 77.502291,lat,lon);
var myLatLng = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker({
position: myLatLng,
icon:image,
map: map,
title: name,
zIndex: 1
});
bank.buildInfoWindow(marker,map,value[n]);
}
return map;
};
Note:This is completely working code only problem is rendering works when i resize broswer manually but not resizing while loading. Please don't mind variable names.All function calls are good except resize event.
I'm using the Google Maps API to develop a web application. I am trying to create a route between two points but for some reason I haven't figured out how create it. Below is my code, please let me know if there is something I am missing. Thank you.
<script>
var Center=new google.maps.LatLng(18.210885,-67.140884);
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var properties = {
center:Center,
zoom:20,
mapTypeId:google.maps.MapTypeId.SATELLITE
};
map=new google.maps.Map(document.getElementById("map"), properties);
directionsDisplay.setMap(map);
var marker=new google.maps.Marker({
position:Center,
animation:google.maps.Animation.BOUNCE,
});
marker.setMap(map);
}
function Route() {
var start = new google.maps.LatLng(18.210885,-67.140884);
var end =new google.maps.latLng(18.211685,-67.141684);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
google.maps.event.addDomListener(window,'load',initialize);
</script>
It works for me if I:
call the Route function
change:
var end =new google.maps.latLng(18.211685,-67.141684);
to:
var end =new google.maps.LatLng(18.211685,-67.141684);
(javascript is case sensitive, the browser reported the error in the javascript console)
working version
code snippet:
var Center = new google.maps.LatLng(18.210885, -67.140884);
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var properties = {
center: Center,
zoom: 20,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map"), properties);
directionsDisplay.setMap(map);
var marker = new google.maps.Marker({
position: Center,
animation: google.maps.Animation.BOUNCE,
});
marker.setMap(map);
Route();
}
function Route() {
var start = new google.maps.LatLng(18.210885, -67.140884);
var end = new google.maps.LatLng(18.211685, -67.141684);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
} else {
alert("couldn't get directions:" + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map"></div>
Good morning.
I have the next code which put some markers in a map from a xml file, every 5 seconds I call again the xml file and I update the position of the markers, but the problem is that the infowindows are not updated. Does anyone knows how to update them=
Here you have the code:
//<![CDATA[
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
map.setZoom(map.getZoom()+2);
}
function initialize() {
// create the map
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(37.169619,-3.756981),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
function getMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
downloadUrl("vehiculos.asp", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" "+speed+" km/h <br/> "+timestamp;
var marker = createMarker(point,alias+" "+imei,html,estado,alias, speed, timestamp, altitude, angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,60)
});
setInterval(function updateMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
downloadUrl("vehiculos.asp", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" a "+speed+" km/h <br/> "+timestamp;
var newLatLng = gmarkers[i].setPosition(point,alias+" "+imei,html,estado,alias,speed,timestamp,altitude,angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}, 5000);
//finish updateMarkers
function createMarker(latlng, imei, html, estado, alias, speed, timestamp, altitude, angle) {
if(estado == 1)
image = '/artworks/icons/truck_green3.png';
else
image = '/artworks/icons/truck_red.png';
var textoLabel= alias+" speed: "+ speed+" km/h";
var contentString = html;
var newLatLng = new MarkerWithLabel({
position: latlng,
icon: image,
// map: map,
draggable: true,
flat: true,
labelContent: textoLabel,
labelAnchor: new google.maps.Point(40, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {
opacity: 0.50
},
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
});
gmarkers.push(newLatLng);
// side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + imei +'<\/a><br>';
}
You are not assigning the event handler in the setInterval function, so no infowindows.
Add this code to the setInterval() after creating the marker
google.maps.event.addListener(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
This may result in a closure problem as you are in a loop. So you can do something like the solutions in this Passing values in for loop to event listeners- Javascript.
this is my example http://gidzior.net/map/v3_animate_marker_directions.html (i'm using placeholder in the input), core of GM code is from geocodezip.com, i develop the code with the great help of Andrew Leach
1500 meters in the animation before the destination is set to zoom could be seen to better reach this destination point, unfortunately, after zoom, animation is not smooth and therefore I set the "step" value to 15, how to reset this value after animation stops
i set step = 15 - if (d>eol-1500 && zoomed!=true) { map.setZoom(15); step = 15; zoomed=true; }
WHOLE SCRIPT
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var position;
var marker = null;
var polyline = null;
var poly2 = null;
var speed = 0.0000005, wait = 1;
var infowindow = null;
var zoomed;
var zoomedd;
var zoomeddd;
var myPano;
var panoClient;
var nextPanoId;
var timerHandle = null;
var size = new google.maps.Size(26,25);
var start_point = new google.maps.Point(0,0);
var foothold = new google.maps.Point(13,15);
var car_icon = new google.maps.MarkerImage("http://gidzior.net/map/car.png", size, start_point, foothold);
function createMarker(latlng, label, html) {
var contentString = '<b>'+label+'</b><br>'+html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: car_icon,
clickable: false,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
return marker;
}
function initialize() {
infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService();
// Create a map and center it on Warszawa.
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
address = 'warszawa'
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
map.setCenter(results[0].geometry.location);
});
// 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.
stepDisplay = new google.maps.InfoWindow();
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
}
var steps = []
function calcRoute(){
if (timerHandle) { clearTimeout(timerHandle); }
if (marker) { marker.setMap(null);}
polyline.setMap(null);
poly2.setMap(null);
directionsDisplay.setMap(null);
polyline = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
poly2 = new google.maps.Polyline({
path: [],
strokeColor: '#FF0000',
strokeWeight: 3
});
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map,
suppressMarkers:true
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var travelMode = google.maps.DirectionsTravelMode.DRIVING
var request = {
origin: start,
destination: end,
travelMode: travelMode,
waypoints: [{
location:new google.maps.LatLng(52.185570, 20.997255),
stopover:false}],
optimizeWaypoints: false
};
// Route the directions and pass the response to a
// function to create markers for each step.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
var bounds = new google.maps.LatLngBounds();
var route = response.routes[0];
startLocation = new Object();
endLocation = new Object();
// For each route, display summary information.
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
// marker = google.maps.Marker({map:map,position: startLocation.latlng});
marker = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
document.getElementById("distance").innerHTML = (polyline.Distance()/1000).toFixed(2)+" km";
map.fitBounds(bounds);
// createMarker(endLocation.latlng,"end",endLocation.address,"red");
map.setZoom(18);
startAnimation();
zoomed=false;
zoomedd=false;
zoomeddd=false;
}
});
}
var step = 50; // 5; // metres
var tick = 100; // milliseconds
var eol;
var k=0;
var stepnum=0;
var speed = "";
var lastVertex = 1;
//=============== animation functions ======================
function updatePoly(d) {
// Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
if (poly2.getPath().getLength() > 20) {
poly2=new google.maps.Polyline([polyline.getPath().getAt(lastVertex-1)]);
// map.addOverlay(poly2)
}
if (polyline.GetIndexAtDistance(d) < lastVertex+2) {
if (poly2.getPath().getLength()>1) {
poly2.getPath().removeAt(poly2.getPath().getLength()-1)
}
poly2.getPath().insertAt(poly2.getPath().getLength(),polyline.GetPointAtDistance(d));
} else {
poly2.getPath().insertAt(poly2.getPath().getLength(),endLocation.latlng);
}
}
function animate(d) {
// alert("animate("+d+")");
if (d>eol) {;
map.panTo(endLocation.latlng);
marker.setPosition(endLocation.latlng);
return;
}
if (d>eol-20000 && zoomeddd!=true) {
map.setZoom(12); // or whatever value
zoomeddd=true;
}
if (d>eol-10000 && zoomedd!=true) {
map.setZoom(13); // or whatever value
zoomedd=true;
}
if (d>eol-1500 && zoomed!=true) {
map.setZoom(15); // or whatever value
step = 15;
zoomed=true;
}
var p = polyline.GetPointAtDistance(d);
map.panTo(p);
marker.setPosition(p);
updatePoly(d);
timerHandle = setTimeout("animate("+(d+step)+")", tick);
}
function startAnimation() {
eol=polyline.Distance();
map.setCenter(polyline.getPath().getAt(0));
// map.addOverlay(new google.maps.Marker(polyline.getAt(0),G_START_ICON));
// map.addOverlay(new GMarker(polyline.getVertex(polyline.getVertexCount()-1),G_END_ICON));
// map.addOverlay(marker);
poly2 = new google.maps.Polyline({path: [polyline.getPath().getAt(0)], strokeColor:"#0000FF", strokeWeight:10});
// map.addOverlay(poly2);
setTimeout("animate(50)",2000); // Allow time for the initial map display
}
I managed to get to this, thanks anyway
i took var step = 50; to the the top
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var position;
var marker = null;
var polyline = null;
var poly2 = null;
var speed = 0.0000005, wait = 1;
var infowindow = null;
var zoomed;
var zoomedd;
var zoomeddd;
var step = 50; // 5; // metres
var myPano;
var panoClient;
var nextPanoId;
var timerHandle = null;
i set step = 50; to the end of calcRoute() function and now animation works fine
I am working with the v3 API and trying to recreate the Store Locator sample (which is v2). I like the way the v2 version works vs the same article changed for v3 API. I have everything working with one exception: when I click the location result it does not open up the marker in the map for that location. Here is my code. I think the problem exists in the CreateSidebarEntry() function. Any help would be greatly appreciated! (you can see it in action here: http://www.webworksct.net/clients/ccparking/partners3.php - just enter "orlando" in the search box and click search to get the results, then click a location in the list on the right...nothing happens).
//<![CDATA[
var map;
var markers = [];
var infoWindow;
var sidebar;
//var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DEFAULT}
});
infoWindow = new google.maps.InfoWindow();
sidebar = document.getElementById("sidebar");
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
sidebar.innerHTML = "";
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
if (markerNodes.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new google.maps.LatLng(40, -100), 4);
return;
}
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
var marker = createMarker(latlng, name, address);
bounds.extend(latlng);
var sidebarEntry = createSidebarEntry(marker, name, address, distance);
sidebar.appendChild(sidebarEntry);
}
map.fitBounds(bounds);
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createSidebarEntry(marker, name, address, distance) {
var div = document.createElement('div');
var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address;
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
google.maps.event.addDomListener(div, 'click', function() {
google.maps.event.trigger(marker, 'click');
});
google.maps.event.addDomListener(div, 'mouseover', function() {
div.style.backgroundColor = '#eee';
});
google.maps.event.addDomListener(div, 'mouseout', function() {
div.style.backgroundColor = '#fff';
});
return div;
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
//]]>
return markers[markers.push(marker)-1];
works and keeps your markers array intact
I found the answer.
In this bit of code:
var marker = createMarker(latlng, name, address);
bounds.extend(latlng);
var sidebarEntry = createSidebarEntry(marker, name, address, distance);
sidebar.appendChild(sidebarEntry);
I was calling createMarker to populate the marker var. I found that it wasn't populating.
In the createMarker function, I needed to make a change so that the function returned a value: markers.push(marker); was changed to return marker; and voila!