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?
Related
I am learning leaflet . My idea was to create map with clusters
, everything works but when I move map new markers keep
overlay old ones.I could see that every time i move map marker gets bolder, so i assume they overlay each other.
How to remove old ones ? I tried everything , cant figure out,
here is code:
var map;
var ajaxRequest;
var plotlist;
var plotlayers=[];
var marker;
var clusters = {}; // key is lat/lon, value is a L.MarkerClusterGroup
var nodecounts = {};// key is lat/lon, value is the number of nodes at that location
var markers = {}; // key is plot id, value is an L.Marker
// Browsable map
function initMap(lat,lon,zoom){
// set up the AJAX stuff
ajaxRequest=GetXmlHttpObject();
if (ajaxRequest==null) { return; }
// set up the map
map = new L.Map('map');
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 20, attribution: osmAttrib});
if (!lat) { lat=44.3008813; lon=-79.6114973; zoom=14; }
map.setView(new L.LatLng(lat,lon),zoom);
map.addLayer(osm);
askForPlots();
map.on('moveend', onMapMove);
}
function askForPlots() {
// request the marker info with AJAX for the current bounds
var bounds=map.getBounds();
var minll=bounds.getSouthWest();
var maxll=bounds.getNorthEast();
$("#regTitle").html("Hello World");
$("#listings").load('/engine/boxlistings.php?w='+minll.lng+'&s='+minll.lat+'&e='+maxll.lng+'&n='+maxll.lat);
var msg='/engine/box.php?w='+minll.lng+'&s='+minll.lat+'&e='+maxll.lng+'&n='+maxll.lat;
ajaxRequest.onreadystatechange = gotPlots;
ajaxRequest.open('GET', msg, true);
ajaxRequest.send(null);
}
function onMapMove(e) {
askForPlots();
}
function gotPlots() {
if (ajaxRequest.readyState!=4 || ajaxRequest.status!=200) return;
var resp = JSON.parse(ajaxRequest.responseText);//.replace(/[^\u000A\u0020-\u007E]/g, "")
var plotlist = resp.plots;
// First, tot up the number at each position, so we know whether to cluster
for (var i=0; i<plotlist.length; i++) {
var plot = plotlist[i];
if (markers[plot.id]) continue;
var ll = new L.LatLng(plot.lat,plot.lon, true);
var key= locationKey(ll);
nodecounts[key] = (nodecounts[key] || 0) + 1;
}
// Custom
var mapcluster = L.markerClusterGroup({ chunkedLoading: true,maxClusterRadius:60 });
for (var i = 0; i < plotlist.length; i++) {
var a = plotlist[i];
var title = a.name;
var marker = L.marker(L.latLng(a.lat, a.lon), {
icon: new L.DivIcon({
className: 'tooltips',
html: ''+
'<div class="triangle" id="'+a.id+'"><strong>'+a.price+'</strong></div>'
})
});
marker.bindPopup(title);
mapcluster.addLayer(marker);
}
map.addLayer(mapcluster);
console.log(mapcluster);
}
function locationKey(ll) { return ll.lat.toFixed(5)+","+ll.lng.toFixed(5); }
// Single plot map
// AJAX support
function GetXmlHttpObject() {
if (window.XMLHttpRequest) { return new XMLHttpRequest(); }
if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); }
return null;
}
Any help appreciated
I use this function:
function removeMarkers() {
map.eachLayer(function (layer) {
layer.remove();
});
}
But it also removes the map so I follow with:
L.imageOverlay(imageUrl, imageBounds).addTo(map);
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.
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 have an array containing several markers for my googlemap.
When I try to add this array to my map I get this error. Any ideas why?
Here is my code:
markers = [];
function create_station_marker(position){
if(position != null){
eval(position);
var latitude = parseFloat(position.latitude);
var longitude = parseFloat(position.longitude);
var new_icon = new GIcon();
new_icon.image = "marker.png";
new_icon.size = new GSize(25,17);
var opt;
opt = {};
opt.icon = new_icon;
var marker = new GMarker(new GLatLng(latitude, longitude),opt);
markers.push(marker);
}
}
And this is where I add my Array to the map:
function load_googlemap() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(48.092757,11.645508), 4);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
for (var i=0; i< markers.length; i++ ) {
try{
map.addOverlay(markers[i]);
alert(markers[i].toSource());
}catch(ex){
//here I get this error!!!
alert(ex);
}
}
}
}
Any ideas about that?
If position is a string containing a JSON representation of the data, you'd have to assign the result of eval() to another variable, e.g.:
if(position != null){
position = eval(position);
// ...
You should, however, parse it properly:
if(position != null){
position = JSON.parse(position);
i would inspect that "position" parameter content once you have an eval over it, it could be the source of error
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.