Display loading message on google maps - javascript

I'm trying to show a (loading....) message while my google map is loading. I have very little experience with maps and Java Script so, please excuse my code. The map was working, before I tried to add a sniplet of code to show a loading message. Now the map doesn't work at all, but I sure it's just an issue of putting the code in the wrong spot. (lack of skills) Can someone please show me what I doing wrong here.
<script type="text/javascript" src="./js/NauticalChartsAPI.js"></script>
<script type="text/javascript" src="./js/gmapsv3ext.js"></script>
<script language="JavaScript" type="text/javascript" src="./js/jquery-1.2.6.js"></script>
<script type="text/javascript">
if (GBrowserIsCompatible()) {
var maploaded = false
var maploadTimer = 0
function load(){
//fire the 'loading' message
checkGoogleMap()
// Global scope
var G = google.maps;
var map;
var api = new NauticalChartsAPI();
/**
* Initialize the Google map.
*/
}
function init() {
/**
* boiler-plate Google Maps code.
*/
var latlng = new G.LatLng(29.37895317, -91.75290604);
var myOptions = {
zoom: 9,
center: new G.LatLng(29.37895317, -91.75290604),
mapTypeId: G.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: G.MapTypeControlStyle.DROPDOWN_MENU
},
};
var map = new G.Map(document.getElementById("map_canvas"),myOptions);
map.addListener('click', (function () {
var converter = function (value, labels) {
var sign = value < 0 ? 0 : 1;
var abs = Math.abs(Math.round(value * 1000000));
var dec = abs % 1000000 / 1000000;
var deg = Math.floor(abs / 1000000);
var min = Math.floor(dec * 60);
var sec = (dec - min / 60) * 3600;
var result = '';
result += deg;
result += "\u00B0";
result += ' ';
result += (min < 10 ? '0' : '') + min;
result += "\u0027";
result += ' ';
result += sec.toFixed(1) * 10;
result += "\u0022";
result += labels[sign];
return result;
};
var marker;
var popup;
return function (e) {
var latLng = e.latLng;
if (!marker) {
marker = new google.maps.Marker({
map: map
});
popup = new google.maps.InfoWindow();
marker.addListener('click', function () {
if (popup && !popup.getMap()) {
popup.open(map, marker);
}
})
} else {
popup.close();
}
var content = converter(latLng.lat(), ['S', 'N']) + '<br>' + converter(latLng.lng(), ['W', 'E']);
marker.setTitle(content);
marker.setPosition(latLng);
popup.setContent('<p>' + content.replace(/ /g, ' ') + '</p>');
popup.open(map, marker);
};
})());
api.setMap(map);
if( api.isLoaded() ) {
// Select the panel we want.
var panel = api.getPanelByFileName('1116A_1');
// Compute and set center/zoom for optimal map coverage
var bounds = panel.getBounds();
map.setCenter(bounds.getCenter());
// add panel as a tile layer
var panelMapType = panel.getTileLayer();
//alert(overlay.setOpacity(.2));
//overlay.setOpacity(1);//this doesn't work!
map.overlayMapTypes.insertAt(0,panelMapType);
}
//add the 'loaded' listener
GEvent.addListener(map, 'tilesloaded', function(){
maploaded = true
});
//add the 'map type changed' listener
GEvent.addListener(map, 'maptypechanged', function(){
resetCheckGoogleMap()
});
//add the 'zoom level changed' listener
//GEvent.addListener(map, 'zoomend', function(){
//resetCheckGoogleMap()
//});
}
function checkGoogleMap() {
//increment the timer every second
maploadTimer = maploadTimer + 1
//specify the target element for our messages
var msg = document.getElementById('msg')
if (maploaded == false) {
//if we dont have a fully loaded map - show the message
$("#msgContainer").slideDown("fast")
//for the first 5 tries, show this message
if (maploadTimer < 5) {
msg.innerHTML = 'Loading map images from Google Maps...';
}
//loop it
setTimeout('checkGoogleMap()',1000);
} else {
//otherwise, show 'loaded' message then hide the message after a second
msg.innerHTML = 'Map loaded.'
maploadTimer = 0;
setTimeout('hideMsg()',1000);
}
//if the timer get up to 20, show a different message
if (maploadTimer >= 20 && maploadTimer <40 ) {
msg.innerHTML = 'Sorry about the wait - your connection to Google Maps is a little slow.';
}
//if it gets to 40 show another different message with a reload link (for what its worth!)
if (maploadTimer >= 40) {
msg.innerHTML = 'Hmmm, still waiting! You can wait a bit longer or you could try reloading the map.';
}
}
function hideMsg() {
$("#msgContainer").slideUp("fast")
}
function resetCheckGoogleMap() {
maploaded = false
maploadTimer = 0;
checkGoogleMap();
}
}
else
alert('api is not loaded!');
}
</script>
<style>
.map_canvas {
position:absolute;
top:50px;
width:100%;
height:90%;
}
}
#msgContainer {
width:100%;
height:30px;
line-height:30px;
background:#FFFFCC;
position:absolute;
z-index:100;
left:0;
top:0;
display:none;
font-size:1.2em;
border-bottom:#FFCC66 1px solid;
}
#msg {
padding-left:10px;
text-align:center;
}
</style>
</head>
<body onLoad="init()">
<div id="msgContainer">
<div id="msg"></div>
</div>
<div id="map_canvas" style="width:100%; height:90%;"></div>
</body>
</html>

GEvent is Google Maps Javascript API v2 syntax, if you are using v3 to equivalent is google.maps.event
//add the 'loaded' listener
GEvent.addListener(map, 'tilesloaded', function(){
maploaded = true
});
//add the 'map type changed' listener
GEvent.addListener(map, 'maptypechanged', function(){
resetCheckGoogleMap()
});
should be:
//add the 'loaded' listener
google.maps.event.addListener(map, 'tilesloaded', function(){
maploaded = true
});
//add the 'map type changed' listener
google.maps.event.addListener(map, 'maptypechanged', function(){
resetCheckGoogleMap()
});

Related

Autoroute step by step using Yours http request has a time lag

I want to set up a html page with gmap and autoroute step by step or point by point. I want to do that using YOURS (OSM) http request options.
It works fine, but at the end of the http request I must set a alert box "alert("OK?);" in order to get the correct route. If I comment that out, the rout will only be set, if I set the next point.
I tried and tried and ... perhaps someone can look over the (extracted) code from a hobby scripter (normally more vba/vbs as js).
best regards Reinhard
Ps: The code example works if you copy out and test local. Don't use "run code snippet" here, the alert box hangs.
<html>
<head>
<title>Google Maps API and Autoroutes</title>
<!--Source code -->
<!-- Style to put some height on the map -->
<style type="text/css">
#map-canvas { height: 500px };
</style>
<!-- Load the Google Maps aPI -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<!-- All of the script for multiple requests -->
<script type="text/javascript">
var map = null;
var info;
var marker;
function init() {
// Some basic map setup (from the API docs)
var mapOptions = {
center: new google.maps.LatLng(51.5, 6.9),
zoom: 13,
mapTypeControl: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
info = document.getElementById('info');
geocoder = new google.maps.Geocoder();
}
//////////////////////routeCalc //////////////
var routeMarkers = [];
var setRM = 0;
function setRouteMarker() {
if (setRM == 0) {
temp = google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng, true)});
//directionsService = new google.maps.DirectionsService();
map.setOptions({draggableCursor:'crosshair'});
setRM = 1;
} else {
map.setOptions({draggableCursor: null});
g.event.removeListener(temp);
setRM = 0;
}
}
var image = {
url: 'http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_red.png',
};
var mIndex = 0;
// OSM YOURS DIRECTION Service//
function addMarker(latlng) {
marker = new google.maps.Marker({
position: latlng,
icon: image,
map: map,
title: latlng.toUrlValue(6),
draggable: true
})
marker.name = mIndex;
mIndex++;
routeMarkers.push(marker);
//info.innerHTML = 'Test:' +mIndex +" / " + routeMarkers.length
testUrl = 'http://www.yournavigation.org/api/1.0/gosmore.php?format=kml&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik'
if (routeMarkers.length == 1) {httpGet(testUrl)}; //for testing
if (routeMarkers.length > 1) {
getRequest();
}
}
function getRequest() {
str = 'http://www.yournavigation.org/api/1.0/gosmore.php?format=kml&'
+ 'flat={startLat}&flon={startLon}&tlat={endLat}&tlon={endLon}&v=bicycle&fast=1&layer=mapnik'
start = routeMarkers[routeMarkers.length - 2].getPosition().toUrlValue(6);;
end = routeMarkers[routeMarkers.length - 1].getPosition().toUrlValue(6);
s = start.split(",");
e = end.split(",");
startLat = s[0]; startLon = s[1];
endLat = e[0]; endLon = e[1];
//alert(endLon);
str = str.replace("{startLat}", startLat);
str = str.replace("{startLon}", startLon);
str = str.replace("{endLat}", endLat);
str = str.replace("{endLon}", endLon);
//alert(str);
//window.clipboardData.setData("Text", str);
data = httpGet(str);
//alert(data.length);
if (data == "x") getRequest();
//alert(data);
coord = data.split("<coordinates>")
coord = coord[1].split("</coordinates>")
coord = coord[0].trim();
//alert(coord);
//window.clipboardData.setData("Text", coord);
var path = [];
var clines = coord.split("\n");
for (i=0; i<clines.length; i++) {
iArray = clines[i].split(",");
lng = iArray[0];
lat = iArray[1];
point = new google.maps.LatLng(lat,lng);
path.push(point)
}
var polyOptions = {
map: map,
path: path,
strokeOpacity: 1.0,
strokeWeight: 3,
editable: false
};
poly = new google.maps.Polyline(polyOptions);
}
function httpGet(theUrl)
{
ajax = new XMLHttpRequest();
ajax.open("GET", theUrl, true);
ajax.setRequestHeader("X-Test","test1");
ajax.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
result = this.responseText;
}else{
alert(this.statusText);
result = "x";
}
}
}
ajax.send(null);
//info.innerHTML = result;
//alert("OK?"); //!! this is needed for correct routing. Why??
return result;
}
// Get the ball rolling and trigger our init() on 'load'
google.maps.event.addDomListener(window, 'load', init);
</script>
</head>
<body>
<!-- Somewhere in the DOM for the map to be rendered -->
<div id="map-canvas"></div>
<TABLE style="width: 512px;">
<TBODY><TR><TD>
<INPUT onclick="setRouteMarker()" type="button" value="Route">
</TD></TR></TBODY></TABLE>
<div id="info" >0 / 0</div>
</body>
</html>
I found a solution. If I change the HTTP request fron asyncron to syncron then I can setup the route click by click correctly. If you are interested in the code (auto routing/direction with multiple, multiple, .. Waypoints) replace the http function from above with the attached http function.
If someone can improve the Http function with some error checking(regarding the comments from W3school), it would be fine.
best regards, Reinhard
function httpGet(theUrl)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", theUrl, false); //asyncron = true doesn't work correct.
xhttp.send();
result = xhttp.responseText;
info.innerHTML = result;
return result;
//Notes from:http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
//Using async=false is not recommended, but for a few small requests this can be ok.
//Remember that the JavaScript will NOT continue to execute, until the server response is ready.
//If the server is busy or slow, the application will hang or stop.
//Note: When you use async=false, do NOT write an onreadystatechange function -
// just put the code after the send() statement:
}

How to create google map markers and polyline after you have removed them?

I am creating a running tracking web app. When you press the start button it starts tracking you. The red marker is the start position and the blue marker tracks your current location and there is a polyline creating a path between the two points.
When I press the "stop" button it deletes the marker's and polyline which is what I want. But when I press the "start" button again after this I want it to just repeat what it did when you first originally press the start button. E.g Create a red marker at the start position and then a blue marker to track the users movements and also create a polyline between the two points.
Currently it is only creating the blue marker and nothing else. How do I fix this?
CodePen Demo
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Runna - Track your run!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href='http://fonts.googleapis.com/css?family=Lato:400,700,900' rel='stylesheet' type='text/css'>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=true&libraries=geometry"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/js.js"></script>
<script src="js/modernizr.js"></script>
</head>
<body>
<div class="wrapper">
<header>
<img src="imgs/logo-blue.png" />
</header>
<div id="map-container">
<div id="map_canvas">Press start to begin</div>
</div>
<div class="show-controls"><i class="fa fa-chevron-up"></i></div>
<section id="control-container">
<div class="column left">
<div id="left-wrapper">
<div class="left-top">
<ul>
<li><b>Distance</b></li>
<li class="distance-total"></li>
</ul>
</div>
<div class="left-bottom">
<ul>
<li><b>Duration</b></li>
<li><span id="stop-watch">00:00:00</span></li>
</ul>
</div>
</div>
</div>
<div class="column middle">
<nav>
<ul>
<li><div><i class="fa fa-chevron-down"></i></div>
<div>START</div>
<div>STOP</div>
</li>
</ul>
</nav>
</div>
<div class="column right">
<div id="right-wrapper">
<div class="right-top">
<ul>
<li><b>Speed</b></li>
<li class="calories-total"></li>
</ul>
</div>
<div class="right-bottom">
<ul>
<li><b>Share</b></li>
<i class="fa fa-facebook-square"></i>
<i class="fa fa-twitter-square"></i>
</ul>
</div>
</div>
</div>
</section>
</div>
</body>
</html>
JS:
// Global Variables ===========================================================================================
var watchID = null;
var geo;
var map;
var startMarker = []; // Red Marker
var endMarker = []; // Blue Marker
var geo_options = {
enableHighAccuracy: true,
maximumAge: 100000,
timeout: 20000
};
var pathLineArray = new Array();
var mypath;
var lastLatLng = pathLineArray[pathLineArray.length - 1];
$(document).ready(function() {
// Show and hide the bottom bar -----------------------------------------------------------------------------
var arrowButton = $('a.arrow');
var controlContainer = $('#control-container');
arrowButton.on('click', function(event) {
event.preventDefault();
controlContainer.fadeOut('fast');
$('.show-controls').show();
$('#map-container').css('height', '87vh');
});
$('.show-controls').on('click', function(event) {
event.preventDefault();
controlContainer.fadeIn('fast');
$('.show-controls').hide();
$('#map-container').css('height', '65vh');
});
// Stop watch script ===========================================================================================
var h2 = document.getElementById('stop-watch'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
seconds = 0,
minutes = 0,
hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h2.innerHTML = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
/* Start button */
start.onclick = function() {
timer();
}
// Resets the stop watch
function resetTimer() {
clearTimeout(t);
h2.innerHTML = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
// End of Stop watch script ===========================================================================================
$('#start').click(startWatching);
if (geo = getGeoLocation()) {
// startWatching(); Only uncomment if you want the map to load straight away upon page load
} else {
alert('Geolocation is not supported');
}
$('#stop').click(function() {
var stopQuestion = confirm("Are you sure you want to stop?");
if (stopQuestion) {
stopWatching();
mypath.setMap(null); // Deletes path/polyline that has been created
startMarker.setMap(null); // Deletes the start red marker
endMarker.setMap(null); // Deletes the end blue marker
resetTimer();
} else {
return;
}
});
}); // Ready block finish here
function getGeoLocation() {
if (navigator.geolocation) {
return navigator.geolocation;
} else {
return "Undefined";
}
}
function startWatching() {
watchID = geo.watchPosition(show_coords, geo_error, geo_options);
// watchID = geo.getCurrentPosition(show_coords, geo_error, geo_options);
}
function stopWatching() {
if (watchID != null) {
geo.clearWatch(watchID);
}
}
function show_coords(position) {
var speed = position.coords.speed;
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
var distance = google.maps.geometry.spherical.computeLength(pathLineArray);
var distanceInKM = distance / 1000; // Converts Meters To KM
var distanceRounded = distanceInKM.toFixed(2); // Allows only two decimal points
var speedInKPH = speed * 3.6; // Converts Meters per second (default value) to kilometers per hour
// Updates the text with the latest distance figure
$('.distance-total').text(distanceRounded + "KM");
$('.calories-total').text(speedInKPH + " kph");
if (map) {
// Makes it so that it doesnt have to reload the map everytime, it just pans to the new position
map.panTo(latlng);
} else {
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
mypath = new google.maps.Polyline({
path: pathLineArray,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
startMarker = new google.maps.Marker({
position: latlng,
map: map
});
}
// Push lat and long coords to this array
pathLineArray.push(latlng);
if (mypath) {
mypath.setPath(pathLineArray);
} else {
mypath = new google.maps.Polyline({
path: pathLineArray,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 4,
map: map,
});
}
if (endMarker && endMarker.setPosition) {
endMarker.setPosition(latlng);
endMarker.setMap(map);
} else {
endMarker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
}
} // End of show_coords(position) function
function geo_error(error) {
switch (error.code) {
case error.TIMEOUT:
alert("geolocation timeout");
break;
case error.POSITION_UNAVAILABLE:
alert("Gelocation position unavailable");
break;
case error.PERMISSION_DENIED:
alert("Permission denied");
break;
default:
alert('Unknown error');
}
}
I have fixed the issue:
I needed to set my map variable back to an empty variable.
Code:
$('#stop').click(function() {
var stopQuestion = confirm("Are you sure you want to stop?");
if (stopQuestion) {
stopWatching();
mypath.setMap(null);
startMarker.setMap(null);
endMarker.setMap(null);
map = ''; // Added this in to set it back to empty
pathLineArray = [];
resetTimer();
}
});

change width of InfoWindow in google maps php api

i'm using Google Maps PHP API, i'm need to change the width of the "infoWindow" that popup then i click on Markers, i tried a few ways do to that but i'm failed.
i'm using some api that i download from the internet, i'm using the function $MAP_OBJECT->addMarkerByCoords().
function getCreateMarkerJS() {
$_output = "
function createMarker(map, point, title, html, icon, icon_shadow, sidebar_id, openers){
var marker_options = {
position: point,
map: map,
title: title};
if(icon!=''){marker_options.icon = icon;}
if(icon_shadow!=''){marker_options.shadow = icon_shadow;}
//create marker
var new_marker = new google.maps.Marker(marker_options);
if(html!=''){
".(($this->info_window)?"
google.maps.event.addListener(new_marker, '".$this->window_trigger."', function() {
infowindow.close();
infowindow.setContent(html);
infowindow.open(map,new_marker);
});
if(openers != ''&&!isEmpty(openers)){
for(var i in openers){
var opener = document.getElementById(openers[i]);
opener.on".$this->window_trigger." = function() {
infowindow.close();
infowindow.setContent(html);
infowindow.open(map,new_marker);
return false;
};
}
}
":"")."
if(sidebar_id != ''){
var sidebar = document.getElementById(sidebar_id);
if(sidebar!=null && sidebar!=undefined && title!=null && title!=''){
var newlink = document.createElement('a');
".(($this->info_window)?"
newlink.onclick=function(){infowindow.open(map,new_marker); return false};
":"
newlink.onclick=function(){map.setCenter(point); return false};
")."
newlink.innerHTML = title;
sidebar.appendChild(newlink);
}
}
}
return new_marker;
}
";
return $_output;
}
The InfoWindow object has a method setOptions({opts}) which allows you to change the InfoWindowOptions. You can use this to set the maxWidth of the InfoWindow.
The actual width of the InfoWinodow is determined by the width of the content, changing the content's width will alter than InfoWindow.

Marker dragging doesn't work on google maps v3 using java script. How to do it?

This is the code that I am using to drop a marker after searching for an address and then dragging it.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Local Search API + Maps API v3 demo</title>
<link href="http://www.google.com/uds/css/gsearch.css" rel="stylesheet" type="text/css"/>
<link href="./places.css" rel="stylesheet" type="text/css"/>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAAjU0EJWnWPMv7oQ-jjS7dYxQ82LsCgTSsdpNEnBsExtoeJv4cdBSUkiLH6ntmAr_5O4EfjDwOa0oZBQ" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
// Our global state
var gLocalSearch;
var gMap;
var gInfoWindow;
var gSelectedResults = [];
var gCurrentResults = [];
var gSearchForm;
// Create our "tiny" marker icon
var gYellowIcon = new google.maps.MarkerImage(
"http://labs.google.com/ridefinder/images/mm_20_yellow.png",
new google.maps.Size(12, 20),
new google.maps.Point(0, 0),
new google.maps.Point(6, 20));
var gRedIcon = new google.maps.MarkerImage(
"http://labs.google.com/ridefinder/images/mm_20_red.png",
new google.maps.Size(12, 20),
new google.maps.Point(0, 0),
new google.maps.Point(6, 20));
var gSmallShadow = new google.maps.MarkerImage(
"http://labs.google.com/ridefinder/images/mm_20_shadow.png",
new google.maps.Size(22, 20),
new google.maps.Point(0, 0),
new google.maps.Point(6, 20));
// Set up the map and the local searcher.
function OnLoad() {
// Initialize the map with default UI.
gMap = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: 'roadmap'
});
// Create one InfoWindow to open when a marker is clicked.
gInfoWindow = new google.maps.InfoWindow;
google.maps.event.addListener(gInfoWindow, 'closeclick', function() {
unselectMarkers();
});
// Initialize the local searcher
gLocalSearch = new GlocalSearch();
gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
}
function unselectMarkers() {
for (var i = 0; i < gCurrentResults.length; i++) {
gCurrentResults[i].unselect();
}
}
function doSearch() {
var query = document.getElementById("queryInput").value;
gLocalSearch.setCenterPoint(gMap.getCenter());
gLocalSearch.execute(query);
}
// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch() {
if (!gLocalSearch.results) return;
var searchWell = document.getElementById("searchwell");
// Clear the map and the old search well
searchWell.innerHTML = "";
for (var i = 0; i < gCurrentResults.length; i++) {
gCurrentResults[i].marker().setMap(null);
}
// Close the infowindow
gInfoWindow.close();
gCurrentResults = [];
for (var i = 0; i < gLocalSearch.results.length; i++) {
gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));
}
var attribution = gLocalSearch.getAttribution();
if (attribution) {
document.getElementById("searchwell").appendChild(attribution);
}
// Move the map to the first result
var first = gLocalSearch.results[0];
gMap.setCenter(new google.maps.LatLng(parseFloat(first.lat),
parseFloat(first.lng)));
}
// Cancel the form submission, executing an AJAX Search API search.
function CaptureForm(searchForm) {
gLocalSearch.execute(searchForm.input.value);
return false;
}
// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result) {
var me = this;
me.result_ = result;
me.resultNode_ = me.node();
me.marker_ = me.marker();
google.maps.event.addDomListener(me.resultNode_, 'mouseover', function() {
// Highlight the marker and result icon when the result is
// mouseovered. Do not remove any other highlighting at this time.
me.highlight(true);
});
google.maps.event.addDomListener(me.resultNode_, 'mouseout', function() {
// Remove highlighting unless this marker is selected (the info
// window is open).
if (!me.selected_) me.highlight(false);
});
google.maps.event.addDomListener(me.resultNode_, 'click', function() {
me.select();
});
document.getElementById("searchwell").appendChild(me.resultNode_);
}
LocalResult.prototype.node = function() {
if (this.resultNode_) return this.resultNode_;
return this.html();
};
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function() {
var me = this;
if (me.marker_) return me.marker_;
var marker = me.marker_ = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(me.result_.lat),
parseFloat(me.result_.lng)),
icon: gYellowIcon, shadow: gSmallShadow, map: gMap});
google.maps.event.addListener(marker, "click", function() {
me.select();
});
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
geocodePosition(marker.getPosition());
});
return marker;
};
// Unselect any selected markers and then highlight this result and
// display the info window on it.
LocalResult.prototype.select = function() {
unselectMarkers();
this.selected_ = true;
this.highlight(true);
gInfoWindow.setContent(this.html(true));
gInfoWindow.open(gMap, this.marker());
};
LocalResult.prototype.isSelected = function() {
return this.selected_;
};
// Remove any highlighting on this result.
LocalResult.prototype.unselect = function() {
this.selected_ = false;
this.highlight(false);
};
// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.html = function() {
var me = this;
var container = document.createElement("div");
container.className = "unselected";
container.appendChild(me.result_.html.cloneNode(true));
return container;
}
LocalResult.prototype.highlight = function(highlight) {
this.marker().setOptions({icon: highlight ? gRedIcon : gYellowIcon});
this.node().className = "unselected" + (highlight ? " red" : "");
}
GSearch.setOnLoadCallback(OnLoad);
//]]>
</script>
</head>
<body style="font-family: Arial, sans-serif; font-size: small;">
<p>Perform a local search on the map below:</p>
<div style="width: 500px;">
<div style="margin-bottom: 5px;">
<div>
<input type="text" id="queryInput" value="pizza" style="width: 250px;"/>
<input type="button" value="Find" onclick="doSearch()"/>
</div>
</div>
<div style="position: absolute; left: 540px;">
<div id="searchwell"></div>
</div>
<div id="map" style="height: 350px; border: 1px solid #979797;"></div>
</div>
</body>
</html>
But the dragging of the marker doesn't work. How to make it work? This code is obviously taken from google samples.
By default markers are not draggable. You must set the draggable-option of the marker(s) to true.

Google map with route-trace loading data instead of adding it on click

In this map
http://econym.org.uk/gmap/example_snappath.htm
source:
<script type="text/javascript">
//<![CDATA[
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(53.7877, -2.9832),13)
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
var dirn = new GDirections();
var firstpoint = true;
var gmarkers = [];
var gpolys = [];
var dist = 0;
GEvent.addListener(map, "click", function(overlay,point) {
// == When the user clicks on a the map, get directiobns from that point to itself ==
if (!overlay) {
if (firstpoint) {
dirn.loadFromWaypoints([point.toUrlValue(6),point.toUrlValue(6)],{getPolyline:true});
} else {
dirn.loadFromWaypoints([gmarkers[gmarkers.length-1].getPoint(),point.toUrlValue(6)],{getPolyline:true});
}
}
});
// == when the load event completes, plot the point on the street ==
GEvent.addListener(dirn,"load", function() {
// snap to last vertex in the polyline
var n = dirn.getPolyline().getVertexCount();
var p=dirn.getPolyline().getVertex(n-1);
var marker=new GMarker(p);
map.addOverlay(marker);
// store the details
gmarkers.push(marker);
if (!firstpoint) {
map.addOverlay(dirn.getPolyline());
gpolys.push(dirn.getPolyline());
dist += dirn.getPolyline().Distance();
document.getElementById("distance").innerHTML="Path length: "+(dist/1000).toFixed(2)+" km. "+(dist/1609.344).toFixed(2)+" miles.";
}
firstpoint = false;
});
GEvent.addListener(dirn,"error", function() {
GLog.write("Failed: "+dirn.getStatus().code);
});
}
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
//]]>
</script>
You can click and add paths that trace routes.
I would like to use the trace-road-functionality, but pre-define the data using coordinates instead. How would I do this?

Categories

Resources