I am trying to reference an array of markers that I created but when I try reference an array element the element receives the message GLOBAL_MARK.0 is null or not an object. I think it might be a scope issue but I'm not sure how to handle it. Here's the code.
var GLOBAL_MARK = "[]"
var vcount = 0;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
MyLat = "47.614495"
MyLng = "-122.341861"
map.setCenter(new GLatLng(MyLat, MyLng), 13);
GDownloadUrl("allmarkers.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var id = markers[i].getAttribute("id");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers [i].getAttribute("lng")));
var marker = createMarker(point, name, address, type, id);
MyAddMarker(marker)
map.addOverlay(marker);
}
});
OutTest()
}
}
function MyAddMarker(marker) {
GLOBAL_MARK[vcount] = marker
vcount = vcount + 1
}
function OutTest() {
alert(GLOBAL_MARK[0].getLatLng)
}
function createMarker(point, name, address, type, id, date1, date2) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address + "<br><br><input type=\"button\" value=\" View Posts \" onclick=\"view_posts('" + id + "','" + type + "','" + date1 + "','" + date2 + "','no')\">"
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
Lots of errors in this code. GLOBAL_MARK was definitely declared wrong to be used as an object like you use it in MyAddMarker(). I'll try to fix as many as I can see by eye without actually being able to run the code:
GLOBAL_MARK = [];
GDownloadUrl("allmarkers.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var id = markers[i].getAttribute("id");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng"))
);
var marker = createMarker(point, name, address, type, id);
MyAddMarker(marker);
map.addOverlay(marker);
}
// when the code gets here, the data from allmarkers.php is done
});
OutTest();
function MyAddMarker(marker) {
GLOBAL_MARK[vcount] = marker;
vcount = vcount + 1;
}
function OutTest() {
alert(GLOBAL_MARK[0].getLatLng);
}
In addition, I don't see a declaration for vcount anywhere.
And, I suspect you're calling OutTest() before the anonymous function in GDownloadUrl has completed. That very well may be an asynchronous function that hasn't completed yet when you call OutTest().
Related
I'm having trouble getting my map to clear the clusters on a new search. Any ideas?
function clearLocations() {
//infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
// clear #side_bar bottom text
document.getElementById("side_bar").innerHTML = "";
// clear .alertBox text
$('.alertBox').html('');
}
function searchLocationsNear(center) {
clearLocations();
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng();
downloadUrl(searchUrl, function (data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
if (markerNodes.length > 0) {
var bounds = new google.maps.LatLngBounds();
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 category = markerNodes[i].getAttribute("category");
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
// createOption(name, distance, i);
createMarker(latlng, name, address, category);
bounds.extend(latlng);
}
map.fitBounds(bounds);
var markerclusterer = new MarkerClusterer(map, markers);
// markerclusterer.setMap(null);
makeSidebar();
} else {
$('.alertBox').html('Sorry, there are no jobs that are close to your location.');
}
});
}
You should try this :
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
markerclusterer.clearMarkers()
}
According to the docs the clusterer can be clear with clearMarkers() method.
UPDATE
Call clear only when we have already create the MarkerClusterer.
if(markerclusterer)
{
clearLocations();
}
I am new to JavaScript.
Writing a script that uses GooogleMaps API
Working OK. Get Lat Lngs from Database, Make markers, put on Map.
Decided to move a function call up a level, (it was in the OnSuccess method of a PageMethod call). Stopped working.
Put in alerts to diagnose. Starts working.
Narrowed down to having alert at top of called function MakeLatLngs().
MakeLatLngs code appears to execute regardless of alert being present or commented out.
It is just that the map displays with alert statement in and doesn't display with alert statement commented out.
The alert is just text and not using any variable. So I am at a loss to understand what is going on here.
The same thing is happening in the function that draws the map DrawMap(). I put an informative alert at the start of the function and the map draws. Leave it out and the map doesn't.
Any clues as to what is going on would be appreciated?
The script is below.
Flow starts at function Initialise at bottom of script.
thanks
var myPositions = [];
var myRoutes = [];
var myString = [];
var myLatLngs = [];
var myTitles = [];
var NumPoints;
var map;
var poly;
var RouteName;
var myMarkers = [];
var myMapCentre = new google.maps.LatLng(-41.2954168187213, 174.767133718655);
function DrawMap() {
alert("Generating Points for " + RouteName);// Need this to display
var thisLatLng = myLatLngs[0];
var myOptions = {
zoom: 8,
center: thisLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
MakeMarkers();
RouteLine();
}
function OnSuccess1(response) {
myPositions = new Array();
myString = response;
NumPoints = response.length;
for (var i = 0; i < NumPoints; i++) {
myPositions[i] = response[i];
}
}
function OnError1(response) {
}
function Marker()
{
this.meterId=0;
this.latLng="";
}
function OnSuccess(response) {
myPositions = new Array();
myString = response;
NumPoints = response.length;
alert("Numpoints is " + NumPoints);
for (var i = 0; i < NumPoints; i++) {
myPositions[i] = response[i];
}
alert("Exiting OnSuccess");
//MakeLatLngs(); //ORIGINAL POSITION OF LATLNG CALL
return true;
}
function setRoute() {
RouteName = prompt(' What route?', '');
}
function OnError(error) {
alert("In Error");
}
function RouteLine() {
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
var path = poly.getPath();
for (var i = 0; i < NumPoints; i++) {
path.push(myLatLngs[i]);
}
}
function MakeLatLngs() {
alert("You need me now " );//Got to have this to display OK when called from LoadData
myLatLngs = new Array();
for (var i = 0; i < NumPoints; i++) {
var sMarker = myPositions[i];
var SeqPos = sMarker.indexOf(";");
var latLngPos = sMarker.indexOf(";", SeqPos + 1);
var marker = sMarker.substring(0, latLngPos);
//alert("Marker is " + marker);
//var Seq = sMarker.substring(latLngPos + 1, SeqPos - latLngPos);
myTitles[i] = marker;
//alert("MeterId is " + marker);
var sLatLng = sMarker.substring(latLngPos + 1)
//alert("SLatLng is " + sLatLng);
var pos = sLatLng.indexOf(",");
//alert("pos is " + pos);
var sLat = sLatLng.substring(0, pos);
//alert("sLat is " + sLat);
var sLng = sLatLng.substring(pos + 1, sLatLng.length - 1);
//alert("sLng is " + sLng);
var lat = parseFloat(sLat);
var lng = parseFloat(sLng);
//alert("Lat is " + lat + " Long is " + lng);
if (!isNaN(lng) && !isNaN(lat) && lat != 0 && lng != 0 ) {
var latlng = new google.maps.LatLng(lat, lng);
myLatLngs[i] = latlng;
}
}
alert("Exiting MakeLatLngs")
}
function MakeMarkers() {
for (var i = 0; i < NumPoints; i++) {
var sTitle = "MyValue " + i;
var marker = new google.maps.Marker({
position: myLatLngs[i],
map: map,
title: myTitles[i]
});
}
}
function LoadData() {
setRoute();//Get the desired route from the user
PageMethods.GetMarkers(RouteName, OnSuccess, OnError);
MakeLatLngs(); //Works here ONLY WHEN AN ALERT IS FIRST LINE in FUNCTION. Orginal call was at end of OnSuccess
//PageMethods.GetRouteBoundaries(OnSuccess1, OnError1);
return false;
}
function initialize() {
LoadData();
DrawMap();
}
google.maps.event.addDomListener(window, 'load', initialize);//yes you do need this with or without <body onload="initialise">
The reason is that your PageMethods.GetMarkers is asynchronous, so the data hasn't loaded when you invoke DrawMap. I guess when you use the alert, it pauses execution long enough for the data to load. Put the DrawMap method inside the OnSuccess of the page method, and that should solve the problem.
I wanted to add a map with some custom markers on it to my project. On localhost everything works fine but when I've sent the code to the production server I got 'Sorry, we don't have map of this region in required scale' (or something similar). This is the code :
<script type='text/javascript'>
var map;
var mapStart = function(){
if(GBrowserIsCompatible()){
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(51.961869,19.134521),6);
map.addControl(new GLargeMapControl());
var ikona1 = new GIcon();
ikona1.image = "{{MEDIA_URL}}images/map_icon_1.png";
ikona1.iconSize = new GSize(36, 30);
ikona1.infoWindowAnchor = new GPoint(16,16);
ikona1.iconAnchor = new GPoint(16,16);
var data_map = {{ properties|safe }}
map.enableDoubleClickZoom();
map.enableContinuousZoom();
var bounds = new GLatLngBounds();
var maxlng =0;
var maxlat=0;
var minlng=0;
var minlat=0;
for (var i=0; i < data_map.length; i++){
var pos_lat = parseFloat(data_map[i]['lat']);
var pos_lon = parseFloat(data_map[i]['long']);
addMarker(pos_lat, pos_lon,{icon:ikona1}, data_map[i]['info_box']
);
if (pos_lat < minlat || minlat==0){ minlat = pos_lat}
if (pos_lat > maxlat || maxlat==0){ maxlat = pos_lat}
if (pos_lon < minlng || minlng==0){minlng = pos_lon}
if (pos_lon > maxlng || maxlng==0){maxlng = pos_lon}
lat = minlat + (( maxlat - minlat)/2);
lng = minlng + (( maxlng - minlng)/2);
var allpoints = new GLatLng(lat,lng);
bounds.extend(allpoints);
}
map.setZoom(map.getBoundsZoomLevel(bounds)-2);
map.setCenter(bounds.getCenter());
}
}
var addMarker = function(lat, lon, options, info_box_html){
point = new GLatLng(lat,lon);
var marker = new GMarker(point, options);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(info_box_html);
});
map.addOverlay(marker);
}
$(document).ready(function(){
mapStart();
});
window.onunload = function (){ GUnload()};
</script>
and I have the following import (with new key generated):
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAA2YOYLBVnylQ7NK445E1_gxQFK8hZs27CqIA3jAe_qRgIGP9GQBTFZjebH-xe-6vEjhK0Pa9agV_Mpg"></script>
data_map has proper form as I've already tested it locally. Also when I've commented out everything apart of creating map and adding control I got clear gray screen Anyone knows this error ?
You have valid coordinates. I wonder if you are sending map.setZoom a valid value. What happens if don't set the zoom level?
For simplicity sake, lets use the XML example on Econym's site.
http://econym.org.uk/gmap/example_map3.htm
Once clicked, I would like icon balloon to be displayed in the middle of the map.
What might I need to add to Mike's code to get this to work? I apologize for asking a lot..
Thanks in advance.
<script type="text/javascript">
//<![CDATA[
if (GBrowserIsCompatible()) {
side_bar
var side_bar_html = "";
var gmarkers = [];
function createMarker(point,name,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
gmarkers.push(marker);
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
return marker;
}
function myclick(i) {
GEvent.trigger(gmarkers[i], "click");
}
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng( 43.907787,-79.359741), 9);
GDownloadUrl("example.xml", function(doc) {
var xmlDoc = GXml.parse(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 GLatLng(lat,lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
var marker = createMarker(point,label,html);
map.addOverlay(marker);
}
document.getElementById("side_bar").innerHTML = side_bar_html;
});
}
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
//]]>
</script>
What you are looking to use is the GMap2.setCenter()(Google API Documentation) function.
So, you should be able to use it as follows:
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml( html );
map.setCenter( marker.getLatLng() );
});
You could, of course, change the order of those actions to your taste.
I had the following HTML page rendering to use the Google Maps API. This has been running for about two months and all the sudden just stopped working. I am trying to get the point with the getLatLng function and it appears to be returning null everytime. Has anyone experienced a similar issue or see anything wrong here? Any help is appreciated.
Using Version 2 of the API. ("v=2")
var map = null;
var geocoder = null;
var marker;
var g_address = "1 Yawkey Way Boston MA";
var toggleState = 0;
var toggleStateDir = 0;
var mapDir;
var gDir;
var geocoderDir = null;
var markerDir;
var g_addressDir = "100 Commonwealth Ave Boston MA";
var panorama;
var currentYaw = 180;
var currentPitch = 0;
var currentZoom = 0;
function initialize()
{
if (GBrowserIsCompatible())
{
// Map
document.getElementById("address").value = g_address;
document.getElementById("addressDir").value = g_addressDir;
map = new GMap2(document.getElementById("map_canvas"));
map.addControl(new GMapTypeControl());
map.addControl(new GScaleControl());
map.addControl(new GLargeMapControl3D());
// Street View
geocoder = new GClientGeocoder();
panorama = new GStreetviewPanorama(document.getElementById("pano"));
// Directions
mapDir = new GMap2(document.getElementById("map_canvas_dir"));
gDir = new GDirections(mapDir, document.getElementById("directions"));
mapDir.addControl(new GMapTypeControl());
mapDir.addControl(new GScaleControl());
mapDir.addControl(new GLargeMapControl3D());
// Traffic overlay
map.setUIToDefault();
var trafficOptions = { incidents: true };
trafficInfo = new GTrafficOverlay(trafficOptions);
mapDir.setUIToDefault();
var trafficOptionsDir = { incidents: true };
trafficInfoDir = new GTrafficOverlay(trafficOptionsDir);
showAddress(g_address, g_addressDir);
}
}
function showAddress(address, addressDir)
{
if (geocoder)
{
geocoder.getLatLng(address,
function(point) {
if (!point) {
alert(address + " not found" + response.Status.code);
}
else {
// Map
g_address = address
map.setCenter(point, 15);
marker = new GMarker(point);
map.addOverlay(marker);
// Street View
document.getElementById("lat").value = point.y;
document.getElementById("long").value = point.x;
document.getElementById("pano").removeAttribute("pano");
panorama.setLocationAndPOV(new GLatLng(point.y, point.x), { yaw: currentYaw, pitch: currentPitch, zoom: currentZoom });
// Directions
gDir.load("from: " + addressDir + " to: " + address, { "locale": "en_US" });
}
}
);
}
}
There's nothing wrong with that code. It works perfectly for me.
Unfortunately, .getLatLng() doesn't return an error code when it fails, and this line will crash when .getLatLng returns nothing:
alert(address + " not found" + response.Status.code);
I can't guess whether there's a problem with your API key (error 610) or if you've been blocked for making too many geocode requests (error 620). I strongly suspect that it will be one of those two because any other error code would be expected to cause the code to fail when I try it.
Try changing your (!point) code to
if (!point) {
geocoder.getLocations(address, function(response) {
alert(address + " not found: " + response.Status.code);
});
}
which uses .getLocations() on the same address and displays the error code.