i am new to programming.. i have this code which gives distance between two points but need to further multiply it by an integer say 10.. the project i am working on is abt calculating distance between two points and multiplying it with fare/Km like Rs.10/km (Indian Rupees) for the same. So if the distance is 30 km the fare would be 30*10 = Rs.300
Thanks in advance
following is the code
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = '';
var destinationA = '';
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
var fromText = document.getElementById('FAdd');
var options = {
componentRestrictions: {country: 'in'}
};var fromAuto = new google.maps.places.Autocomplete(fromText, options);
fromAuto.bindTo('bound', map);
var toText = document.getElementById('TAdd');
var toAuto = new google.maps.places.Autocomplete(toText, options);
toAuto.bindTo('bound', map);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [document.getElementById("FAdd").value],
destinations: [document.getElementById("TAdd").value],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += results[j].distance.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
I use an Ajax call to PHP, and haven't yet used getDistanceMatrix(), but this should be an easy fix.
First, if you know you will always only have one origin and one destination, you don't need the "for" loop in your callback function. Second, you're taking the distance text rather than the distance value.
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
[...]
} else {
deleteOverlays();
var outputDiv = document.getElementById('outputDiv'),
origin = response.originAddresses[0],
destination = response.destinationAddresses[0],
result = response.rows[0].elements[0],
distance = result.distance.value,
text = result.distance.text,
price = 10 * distance;
outputDiv.innerHTML = '<p>' + text + ': Rs.' + price + '</p>';
addMarker(origin, false);
addMarker(destination, false);
}
}
I haven't tested this, so it probably needs to be tweaked. ( See https://developers.google.com/maps/documentation/distancematrix/#DistanceMatrixResponses )
Related
I'm trying to get the exchanges in ripple and I found this data API and its working. But I want to use the ripple websocket tool for some reasons. Is there any websocket equivalent for this data API?
I think there is equivalent if you use "tx_history" command in the socket but Sorry to tell you that the json result are not equal to your specific data result.
ripple data apiv2 is being played by ajax. see the result json formatter in ripple for exchange:
} else if (resp.rows.length) {
resp.rows[0] = {
base_currency: resp.rows[0].base_currency,
base_issuer: resp.rows[0].base_issuer,
base_amount: resp.rows[0].base_amount,
counter_amount: resp.rows[0].counter_amount,
counter_currency: resp.rows[0].counter_currency,
counter_issuer: resp.rows[0].counter_issuer,
rate: resp.rows[0].rate,
executed_time: resp.rows[0].executed_time,
ledger_index: resp.rows[0].ledger_index,
buyer: resp.rows[0].buyer,
seller: resp.rows[0].seller,
taker: resp.rows[0].taker,
provider: resp.rows[0].provider,
autobridged_currency: resp.rows[0].autobridged_currency,
autobridged_issuer: resp.rows[0].autobridged_issuer,
offer_sequence: resp.rows[0].offer_sequence,
tx_type: resp.rows[0].tx_type,
tx_index: resp.rows[0].tx_index,
node_index: resp.rows[0].node_index,
tx_hash: resp.rows[0].tx_hash
};
}
res.csv(resp.rows, filename);
} else {
res.json({
result: 'success',
count: resp.rows.length,
marker: resp.marker,
exchanges: resp.rows
});
} }
and it can be only access by get url :
route: '/v2/exchanges/{:base}/{:counter}'
that is bind in there server.js:
app.get('/v2/exchanges/:base/:counter', routes.getExchanges);
and last hint this is their database query using hbase:
HbaseClient.getExchanges = function (options, callback) {
var base = options.base.currency + '|' + (options.base.issuer || '');
var counter = options.counter.currency + '|' + (options.counter.issuer
||''); var table;
var keyBase;
var startRow;
var endRow;
var descending;
var columns;
if (counter.toLowerCase() > base.toLowerCase()) {
keyBase = base + '|' + counter;
} else {
keyBase = counter + '|' + base;
options.invert = true; }
if (!options.interval) {
table = 'exchanges';
descending = options.descending ? true : false;
options.unreduced = true;
//only need certain columns
if (options.reduce) {
columns = [
'd:base_amount',
'd:counter_amount',
'd:rate',
'f:executed_time',
'f:buyer',
'f:seller',
'f:taker'
];
}
} else if (exchangeIntervals.indexOf(options.interval) !== -1) {
keyBase = options.interval + '|' + keyBase;
descending = options.descending ? true : false;
table = 'agg_exchanges';
} else {
callback('invalid interval: ' + options.interval);
return; }
startRow = keyBase + '|' + options.start.hbaseFormatStartRow();
endRow = keyBase + '|' + options.end.hbaseFormatStopRow();
if (options.autobridged) {
options.filterstring = "DependentColumnFilter('f', 'autobridged_currency')";
if (columns) {
columns.push('f:autobridged_currency');
} }
this.getScanWithMarker(this, {
table: table,
startRow: startRow,
stopRow: endRow,
marker: options.marker,
limit: options.limit,
descending: descending,
columns: columns,
filterString: options.filterstring }, function (err, resp) {
if (!resp) {
resp = {rows: []};
}
if (!resp.rows) {
resp.rows = [];
}
if (options.reduce && options.unreduced) {
if (descending) {
resp.rows.reverse();
}
resp.reduced = reduce(resp.rows);
} else if (table === 'exchanges') {
resp.rows = formatExchanges(resp.rows);
} else {
resp.rows = formatAggregates(resp.rows);
}
callback(err, resp); });
/** * formatExchanges */
function formatExchanges (rows) {
rows.forEach(function(row) {
var key = row.rowkey.split('|');
delete row.base_issuer;
delete row.base_currency;
delete row.counter_issuer;
delete row.counter_currency;
row.base_amount = parseFloat(row.base_amount);
row.counter_amount = parseFloat(row.counter_amount);
row.rate = parseFloat(row.rate);
row.offer_sequence = Number(row.offer_sequence || 0);
row.ledger_index = Number(row.ledger_index);
row.tx_index = Number(key[6]);
row.node_index = Number(key[7]);
row.time = utils.unformatTime(key[4]).unix();
});
if (options.invert) {
rows = invertPair(rows);
}
return rows; }
/** * formatAggregates */
function formatAggregates (rows) {
rows.forEach(function(row) {
var key = row.rowkey.split('|');
row.base_volume = parseFloat(row.base_volume),
row.counter_volume = parseFloat(row.counter_volume),
row.buy_volume = parseFloat(row.buy_volume),
row.count = Number(row.count);
row.open = parseFloat(row.open);
row.high = parseFloat(row.high);
row.low = parseFloat(row.low);
row.close = parseFloat(row.close);
row.vwap = parseFloat(row.vwap);
row.close_time = Number(row.close_time);
row.open_time = Number(row.open_time);
});
if (options.invert) {
rows = invertPair(rows);
}
return rows; }
/** * if the base/counter key was inverted, we need to swap * some of the values in the results */
function invertPair (rows) {
var swap;
var i;
if (options.unreduced) {
for (i=0; i<rows.length; i++) {
rows[i].rate = 1/rows[i].rate;
//swap base and counter vol
swap = rows[i].base_amount;
rows[i].base_amount = rows[i].counter_amount;
rows[i].counter_amount = swap;
//swap buyer and seller
swap = rows[i].buyer;
rows[i].buyer = rows[i].seller;
rows[i].seller = swap;
}
} else {
for (i=0; i<rows.length; i++) {
//swap base and counter vol
swap = rows[i].base_volume;
rows[i].base_volume = rows[i].counter_volume;
rows[i].counter_volume = swap;
//swap high and low
swap = 1/rows[i].high;
rows[i].high = 1/rows[i].low;
rows[i].low = swap;
//invert open, close, vwap
rows[i].open = 1/rows[i].open;
rows[i].close = 1/rows[i].close;
rows[i].vwap = 1/rows[i].vwap;
//invert buy_volume
rows[i].buy_volume /= rows[i].vwap;
}
}
return rows; }
/** * reduce * reduce all rows */
function reduce (rows) {
var buyVolume = 0;
var reduced = {
open: 0,
high: 0,
low: Infinity,
close: 0,
base_volume: 0,
counter_volume: 0,
buy_volume: 0,
count: 0,
open_time: 0,
close_time: 0
};
rows = formatExchanges(rows);
// filter out small XRP amounts
rows = rows.filter(function(row) {
if (options.base.currency === 'XRP' && row.base_amount < 0.0005) {
return false;
} else if (options.counter.currency === 'XRP' && row.counter_amount < 0.0005) {
return false;
} else {
return true;
}
});
if (rows.length) {
reduced.open_time = moment.unix(rows[0].time).utc().format();
reduced.close_time = moment.unix(rows[rows.length-1].time).utc().format();
reduced.open = rows[0].rate;
reduced.close = rows[rows.length -1].rate;
reduced.count = rows.length;
} else {
reduced.low = 0;
return reduced;
}
rows.forEach(function(row) {
reduced.base_volume += row.base_amount;
reduced.counter_volume += row.counter_amount;
if (row.rate < reduced.low) reduced.low = row.rate;
if (row.rate > reduced.high) reduced.high = row.rate;
if (row.buyer === row.taker) {
reduced.buy_volume += row.base_amount;
}
});
reduced.vwap = reduced.counter_volume / reduced.base_volume;
return reduced; } };
Maybe you should make a custom websocket that make your RPC call upgrade to 1.1 http protocol (ws).
In nodejs you can simply
// for http
var http = require('http');
// for websocket
var ws = require("nodejs-websocket")
var options = {
host: 'URL-RPC-HERE',
port: '80',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
var req = http.request(options, function(res) {
// after getting the response wich is the <res>
// we can upgrade it to ws
upToWebsocket(res);
});
//Upgrade to websocket
var upToWebsocket = function(json) {
var server = ws.createServer(function (conn) {
conn.on("json", function (str) {
conn.sendText(str.toUpperCase()+"!!!")
})
conn.on("close", function (code, reason) {
console.log("Connection closed")
})
}).listen(8001)
}
And also if you have Rippled running on a server this does not help because there's no RPC or WS that supports exchange API.
my calculated route works good so far, but I have some trouble with my destination address.
When the destination is within a pedestrian area (city center), this destination (lat, long) will set to the next valid street. This is probably how it supposed to be, but it's important that I get the route until the specific destination address. What I want: E.g. I drive into the pedestrian area or I drive as far as possible by car and then walk to the destination.
Anyone has an idea how I can solve this problem? I am using the following code, the code works so that is not the problem:
<script type="text/javascript">
var directionsDisplay = new google.maps.DirectionsRenderer({
animation: google.maps.Animation.DROP,
draggable: true
});
var directionsService = new google.maps.DirectionsService();
var map;
var geocoder;
var resultsInput;
var question;
var routeStart, routeEnd;
var travMode;
var frage_gruppen_nr;
var zsf1,zsf2;
var zentrieren;
function initialize() {
geocoder = new google.maps.Geocoder();
routeStart = $('.multiple-short-txt:eq(0) .text:eq(0)');
routeEnd = $('.multiple-short-txt:eq(0) .text:eq(1)');
coords_field_map = $('.text-short:eq(1) .text:eq(0)');
coords_field_map.hide();
zsf1 = $('.multiple-short-txt:eq(1) .text:eq(0)');
zsf2 = $('.multiple-short-txt:eq(1) .text:eq(1)');
var aktuelle_frage = 'r1';
var frage_gruppen_nr = parseInt(aktuelle_frage.substr(1));
frage_gruppen_nr = frage_gruppen_nr - 1;
if(frage_gruppen_nr>1){
routeStart.val('xxxx');
var coords;
var ziel_vorfrage = 'abc';
alert(ziel_vorfrage);
geocoder.geocode( { 'address': ziel_vorfrage}, function(results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords = String(results1[0].geometry.location)
}
});
zentrieren = new google.maps.LatLng(coords);
}else{
zentrieren = new google.maps.LatLng(49.759578, 6.644134);
}
travMode = document.getElementsByTagName("SELECT")[0];
question = '{SGQ}_c';
var mapOptions = {
zoom:12,
center: zentrieren
};
map = new google.maps.Map(document.getElementById('gmap_canvas_'+question), mapOptions);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function(event) {
var directions = this.getDirections();
var overview_path = directions.routes[0].overview_path;
var startingPoint = overview_path[0];
var destination = overview_path[overview_path.length - 1];
if (typeof startLatlng === 'undefined' || !startingPoint.equals(startLatlng)) {
startLatlng = startingPoint;
getLocationName(startingPoint, function(name) {
routeStart.val(name);
});
}
if (typeof endLatlng === 'undefined' || !destination.equals(endLatlng)) {
endLatlng = destination;
getLocationName(destination, function(name) {
routeEnd.val(name);
});
}
//alert('startpoint: '+startingPoint);
calculateDistances(startingPoint, destination);
});
directionsDisplay.setMap(map);
resultsInput = $('.text-long:eq(0) .textarea');
$(resultsInput).attr('readonly', true);
}
function calcRoute() {
var coords;
var coords2;
var start = routeStart.val();
geocoder.geocode( { 'address': start}, function(results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords = String(results1[0].geometry.location)
}
else {
alert('Die Startadresse konnte nicht gefunden werden.');
}
});
var end = routeEnd.val();
geocoder.geocode( { 'address': end}, function(results2, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
coords2 = String(results2[0].geometry.location)
}
else {
alert('Die Zieladresse konnte nicht gefunden werden.');
}
});
var selectedMode;
if(travMode.value == 1){
selectedMode = 'DRIVING';
}else if(travMode.value == 2){
selectedMode = 'BICYCLING';
}else if(travMode.value == 3){
selectedMode = 'TRANSIT';
}else if(travMode.value == 4){
selectedMode = 'WALKING';
}
//
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function calculateDistances(origin, destination) {
var selectedMode;
//select travel mode
if(travMode.value == 1){
selectedMode = 'DRIVING';
}else if(travMode.value == 2){
selectedMode = 'BICYCLING';
}else if(travMode.value == 3){
selectedMode = 'TRANSIT';
}else if(travMode.value == 4){
selectedMode = 'WALKING';
}
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode[selectedMode],
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
$(resultsInput).val('Startaddresse: '+origins[i]+'\n\nReiseziel: '+destinations[j]+'\n\nDistanz: '+results[j].distance.text+'\n\nZeit: '+results[j].duration.text+'');
//save result to fields
zsf1.val(results[j].distance.text);
zsf2.val(results[j].duration.text);
}
}
}
}
function getLocationName(latlng, callback) {
geocoder.geocode({
location: latlng
}, function(result, status) {
if (status === google.maps.GeocoderStatus.OK) {
var i = -1;
console.log(result);
// find the array index of the last object with the locality type
for (var c = 0; c < result.length; c++) {
for (var t = 0; t < result[c].types.length; t++) {
if (result[c].types[t].search('locality') > -1) {
i = c;
}
}
}
var locationName = result[0].formatted_address;
callback(locationName);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I have created a json file containing my Sql Server datas. With the XmlHttpRequest's GET method, I am reading json file and iterating and saving those records to my IndexedDB.. Everything is working fine.. After the end of the iteration, I wrote a code to alert the user.. But the alert message is displayed very quickly, but when I see it in the console window, the saving operation is till processing.. I want to alert the user, only after the operation is completed..
My code is,
if (window.XMLHttpRequest) {
var sFileText;
var sPath = "IDBFiles/Reservation.json";
//console.log(sPath);
var xhr = new XMLHttpRequest();
xhr.open("GET", sPath, 1);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText != "") {
sFileText = xhr.responseText;
//console.log(sFileText);
var val = JSON.parse(sFileText);
var i = 0;
var value = val.length;
for(var i in val)
{
var code = val[i].RTM_res_category_code;
var desc = val[i].RTM_res_category_edesc;
addReserv(code, desc);
}
if(i >= value-1) {
console.log("Reservation Load Completed... "+i);
document.getElementById("status").innerHTML = "Reservation Loading Success...";
}
}
}
}
xhr.send();
}
//Passing Parameters to Reservation
function addReserv(code, desc)
{
document.querySelector("#status").innerHTML = "Loading Reservation.. Please wait...";
var trans = db.transaction(["Reservation"], "readwrite");
var store = trans.objectStore("Reservation");
//console.log(store);
var reserv={ RTM_res_category_code : code, RTM_res_category_edesc : ''+desc+'' };
var request = store.add(reserv);
request.onerror = function(e) {
console.log(e.target.error.name);
document.querySelector("#status").innerHTML = e.target.error.name;
}
request.onsuccess = function(e) {
console.log("Reservation Saved Successfully.");
//document.querySelector("#status").innerHTML = "Reservation Loaded Successfully.";
}
}
Thanks for the question.
What you are currently doing works, but the alert comes to soon because of the async nature of the IDB.
What you should to avoid this.
1. Create your transaction only once.
2. Do all your operations in this one transaction.
3. The transaction object has an oncomplete callback you can use to notify the user.
Concrete on your example. Instead of looping over the items in the ajax callback, pass the collection to your add method and loop there
if (window.XMLHttpRequest) {
var sFileText;
var sPath = "IDBFiles/Reservation.json";
//console.log(sPath);
var xhr = new XMLHttpRequest();
xhr.open("GET", sPath, 1);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText != "") {
sFileText = xhr.responseText;
//console.log(sFileText);
var val = JSON.parse(sFileText);
import(val);
}
}
}
xhr.send();
}
function import(values)
{
document.querySelector("#status").innerHTML = "Loading Reservation.. Please wait...";
var trans = db.transaction(["Reservation"], "readwrite");
var store = trans.objectStore("Reservation");
var i = 0;
var value = val.length;
for(var i in val)
{
var code = val[i].RTM_res_category_code;
var desc = val[i].RTM_res_category_edesc;
var reserv={ RTM_res_category_code : code, RTM_res_category_edesc : ''+desc+'' };
var request = store.add(reserv);
request.onerror = function(e) {
console.log(e.target.error.name);
document.querySelector("#status").innerHTML = e.target.error.name;
}
request.onsuccess = function(e) {
console.log("Reservation Saved Successfully.");
//document.querySelector("#status").innerHTML = "Reservation Loaded Successfully.";
}
}
trans.oncomplete = function () {
console.log("Reservation Load Completed... "+i);
document.getElementById("status").innerHTML = "Reservation Loading Success...";
}
}
I am using the blowing script to get all store around position wit 20 mile and working well but when try to using it to get postal_code do not working
how i get all postal code around center with specific distance
code:
<script type="text/javascript" language="javascript">
var lat = "";
var lng = "";
function latClick(glocation) {
var a = new google.maps.Geocoder();
a.geocode({ 'address': glocation }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
var c = results;
else
c = "We couldn't find that location. Please try again."
lat = c[0].geometry.location.lat();
lng = c[0].geometry.location.lng();
var pyrmont = new google.maps.LatLng(lat, lng);
//sll=30.04443,31.234217&sspn=0.036703,0.084543&geocode=FU1wygEdO5jcAQ%3BFQRxygEdgJ7cASnrviELpj9YFDG6O0LolrLfeQ&mra=mift&
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 200,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
});
}
var map;
var infowindow;
function initialize() {
latClick("Jersey City, NJ 07306, United States");
}
function callback(results, status) {
var x = "";
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
x = x + results[i].name + ", ";
}
alert(x);
}
}
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);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
To start off with, I would like to say that I have been looking on the internet for a really long time and have been unable to find the answer, hence my question here.
My latest school project is to create an admin page for adding articles to a database, the articles are connected to a point on a google map. The requirement for adding the point on the map is that the user is able to click the map once and the marker is produced, if the map is clicked a second time the first marker is moved to the second location. (this is what I am struggling with.)
The problem is, as the code is now, I get the error that markersArray is undefined. If I place the var markersArray = new Array; underneath the eventListener then I get an error that there is something wrong the main.js (googles file) and markersArray[0] is undefined in the second if.
By the way, I have to use google maps API v2, even though it is old.
<script type="text/javascript">
//<![CDATA[
var map;
var markers = new Array;
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
if (this.counter == 0) {
if (latlng) {
var marker = new GMarker(latlng);
latlng1 = latlng;
this.map.addOverlay(marker);
this.counter++;
markers.push(marker); //This is where I get the error that markersArray is undefined.
}
}
else if (this.counter == 1) {
if (latlng){
alert (markers[0]);
this.map.removeOverlay(markers[0]);
var markers = [];
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}
I solved the problem. I'm not exactly sure why it worked but this is what it looks like now:
var markersArray = [];
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var type = Articles[i].getAttribute("type");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
var marker = new GMarker(latlng);
if (this.counter == 0) {
if (latlng) {
latlng1 = latlng;
this.map.addOverlay(marker);
markersArray.push(marker);
this.counter++;
}
}
else if (this.counter == 1) {
if (latlng){
this.map.removeOverlay(markersArray[0]);
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}