auto update marker with AJAX - javascript

I'm using this code to get gps data from (db.php from database), I need to update marker without refreshing the page. I tested setInterval (function ()), it works but it updates the whole page (map + marker). I need to update just the position of marker (variable uluru) but my problem is that the variable uluru is local
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="map"><b></b></div>
<div id="map2"><b>
</b></div>
<script>
var markers = [];
function loadmap(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
var latt = myObj.name;
var longg = myObj.name2;
uluru = {lat:+latt , lng:+longg };
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center:uluru,
});
addmarker(uluru);
}
};
xmlhttp.open("GET","db.php?q=",true);
xmlhttp.send();
}
function addmarker(location){
var marker = new google.maps.Marker({ position: location, map: map });
markers.push(marker);
}
setInterval(function(){ loadmap() }, 1000);
</script>
<script
async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD9J11XCcYDoT8-s0BD9sR4ARzIUmpI&callback=loadmap">
</script>
</body>
</html>

Related

RTKPLOT not showing google map

I am using RTKLIB feature RTKPLOT. Google map is not enabled in it because it requires API key. I inserted google map API key in given htm file but a blank screen is shown while showing coordinates. The header part of htm file is first like this
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false"
type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
After that i replaced it for inserting API key as follows.
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false"
->
<script src="http://maps.google.com/maps/api/js?key={XXXXXXXXXXXXXXXXXXXXXXXXXXXXX_XXXXXXXXX}&v=3&sensor=false"
tell me where I am wrong .
complete code is
<html>
<head>
<title>RTKLIB_GM</title>
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false"
type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
var map = null;
var marks = [];
var markh = null;
var markz = 0;
var info = null;
var icon0="http://maps.google.co.jp/mapfiles/ms/icons/red-dot.png";
var icon1="http://maps.google.co.jp/mapfiles/ms/icons/yellow-dot.png";
function init() {
var opt = {
center: new google.maps.LatLng(0,0),
zoom: 2, minZoom: 2,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),opt);
document.getElementById('state').value='1';
}
function SetView(lat,lon,zoom) {
if (map == null) return;
map.setCenter(new google.maps.LatLng(lat,lon));
map.setZoom(zoom);
}
function SetCent(lat,lon) {
if (map == null) return;
map.setCenter(new google.maps.LatLng(lat,lon));
}
function SetZoom(zoom) {
if (map == null) return;
map.setZoom(zoom);
}
function ClearMark(lat,lon,title) {
for (var i in marks) {
marks[i].setMap(null);
}
marks.length = 0;
markh = null;
}
function AddMark(lat,lon,title,msg) {
var pos = new google.maps.LatLng(lat,lon);
var opt = {map: map, position: pos, title: title, icon: icon1};
var mark = new google.maps.Marker(opt);
if (title == "SOL2") mark.setIcon(icon0);
google.maps.event.addListener(mark,'click',function(event) {
if (info) {info.close();}
info = new google.maps.InfoWindow({content: msg});
info.open(mark.getMap(),mark);
});
marks.push(mark);
}
function PosMark(lat,lon,title) {
for (var i in marks) {
if (marks[i].title==title) {
marks[i].setPosition(new google.maps.LatLng(lat,lon));
break;
}
}
}
function ShowMark(title) {
for (var i in marks) {
if (marks[i].title==title) {
marks[i].setVisible(true);
break;
}
}
}
function HideMark(title) {
for (var i in marks) {
if (marks[i].title==title) {
marks[i].setVisible(false);
break;
}
}
}
</script>
</head>
<body style="margin: 0;"; scroll="no"; onload="init()">
<div id="map" style="height: 100%; width: 100%;"> </div>
<input id="state" type="hidden" value="0">
</body>
</html>
Assuming you are on Windows. You need to add a register key for the software to work.
Add the following entry of Windows registries by regedit (Registry Editor) to run the WebBrowser component on RTKPlot.exe as IE 11.
Key: KEY_LOCAL_MACHINE - SOFTWARE - Wow6432Node - Microsoft - Internet Explorer - MAIN - FeatureControl - FEATURE_BROWSER_EMULATION
Name: rtkplot.exe
Type: REG_DWORD
Data: 11000 (decimal)
http://www.rtklib.com/rtklib_support.htm - the same issue exists for NTRIP Browser (srctblbrows.exe)
This made it work on my machine, I had the same issue you had.

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

Display loading message on google maps

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

Multiple Locations in Bing Maps in an iframe

I'm trying to get this piece of code to work in an iframe, but I always get the error:
ReferenceError: GetMap is not defined
I am not an advanced programmer, so I have no idea why it works alone, but not in an iframe (and nobody seems to have the same problem)! Help would be very appreciated.
PS: The programming code is mostly from YoYoMyo (who posted it on stackoverflow), I just adapted it for my use
<html>
<head>
<script charset="UTF-8" type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript" language="JavaScript">
function GetMap() {
var longitude = new Array();
var latitude = new Array();
var title = new Array();
var description = new Array();
longitude[0] = 47.5564154 //two defined locations
latitude[0] = 7.59245395
title[0] = "Basler Münster"
description[0] = "Basel"
longitude[1] = 47.55330556 //second defined Location
latitude[1] = 7.59001851
title[1] = "Theater Basel"
description[1] = "Basel"
var total = 2 //number of locations
var pinInfoBox; //the pop up info box
var infoboxLayer = new Microsoft.Maps.EntityCollection();
var pinLayer = new Microsoft.Maps.EntityCollection();
var apiKey = "AmpgeSj6OVb9ILPwvjyIfwM3qmqm5yccyNGR_mxmbpw2znYZoXxQAz_KVbc84XCC";
map = new Microsoft.Maps.Map(document.getElementById("map"), {credentials: apiKey});
// Create the info box for the pushpin
pinInfobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), { visible: false });
infoboxLayer.push(pinInfobox);
for (var i = 0 ; i < total; i++){
//add pushpins
var latLon = new Microsoft.Maps.Location(longitude[i], latitude[i]);
var pin = new Microsoft.Maps.Pushpin(latLon);
pin.Title = title[i];//usually title of the infobox
pin.Description = description[i]; //information you want to display in the infobox
pinLayer.push(pin); //add pushpin to pinLayer
Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);
}
map.entities.push(pinLayer);
map.entities.push(infoboxLayer);
map.setView({zoom: 15, center: new Microsoft.Maps.Location(47.55330556, 7.59001851)});
}
function displayInfobox(e)
{
pinInfobox.setOptions({title: e.target.Title, description: e.target.Description, visible:true, offset: new Microsoft.Maps.Point(0,25)});
pinInfobox.setLocation(e.target.getLocation());
}
function hideInfobox(e)
{
pinInfobox.setOptions({ visible: false });
}
</script>
<style>
#map { position: relative; top: 0; left: 0; width: 100%; height: 800px; border:none;}
</style>
</head>
<body onload="GetMap()">
<div id="some stuff" style="width=100%; height:80px">
some text
</div>
<div id="map" style="width=100%; height:800px">
</div>
<div id="some more stuff" style="width=100%; height:80px">
some more text to read
</div>
</body>
</html>
The code looks fine and I'm unable to reproduce the error you are seeing.

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.

Categories

Resources