Google Maps JS API with KML layer control - google-maps

I have found different solutions for switching KmlLayers on/off using JavaScript. All scripts that I've seen require separate functions for each layer, but I want to have only one function for all layers so when adding a new layer to my web page I don't have to edit the existing JavaScript code.
My code:
<!DOCTYPE html>
<html><head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<style type="text/css">
* {margin:0; padding:0; border:0; outline:0; font-size:100%;
vertical-align:baseline}
html, body {width:100%; height:100%}
#map {width:100%; height:95%}
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false&language=lv">
</script>
<script type="text/javascript">
var G = google.maps; var kml = null; var show = false;
function toggle() {
var tr = this.rel;
if (!tr) {
tr = new G.KmlLayer('http://www.eiranet.lv/kartes/Anjo/kmz/' +
this.id + '.kmz', {preserveViewport:true})
};
show = !show;
if (show) {
tr.setMap(map)
}
else {
tr.setMap(null)
};
};
function initialize() {
var layers = document.getElementsByTagName('input');
var options = {
center: new G.LatLng(34.9, 137.3),
zoom: 10,
mapTypeId: G.MapTypeId.TERRAIN,
scaleControl: true,
overviewMapControl: true,
mapTypeControlOptions: {
style:G.MapTypeControlStyle.DROPDOWN_MENU }
};
map = new G.Map(document.getElementById('map'), options);
for (var i=0; i<layers.length; i++) {
layers[i].type = 'checkbox';
G.event.addDomListener(layers[i], 'click', toggle)
};
};
G.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
<input id="Didzis_21.03-03.04" rel="d1"/>
<input id="Didzis_04.04-17.04" rel="d2"/>
<input id="Didzis_18.04-01.05" rel="d3"/>
<input id="Didzis_02.05-15.05" rel="d4"/>
</body></html>
Here is my problem: actually I can switch multiple layers on but I can't turn them off. I think that all of the code is good except function toggle(). Also, it would be good if 'rel' attributes wouldn't be necessary, only 'id'.

It looks like each KmlLayer that you create gets orphaned; they are assigned to a function local var named tr, but then never assigned to anything that will remain available across multiple calls to toggle(). I suggest some changes to the toggle() function:
function toggle() {
if (!this.kmlLayer ) {
this.kmlLayer = new G.KmlLayer(
'http://www.eiranet.lv/kartes/Anjo/kmz/' + this.id + '.kmz',
{ preserveViewport:true } );
}
show = !show;
if (show) {
this.kmlLayer.setMap(map)
}
else {
this.kmlLayer.setMap(null)
};
};
After reviewing your page in some more detail, I suggest additional changes:
function toggle() {
if (!this.kmlLayer ) {
this.kmlLayer = new G.KmlLayer(
'http://www.eiranet.lv/kartes/Anjo/kmz/' + this.id + '.kmz',
{ preserveViewport:true } );
this.displayIsOn = false;
}
//show = !show; -- Remove this line, it is causing display state problems
if ( this.displayIsOn ) {
this.kmlLayer.setMap( null );
this.displayIsOn = false;
}
else {
this.kmlLayer.setMap( map );
this.displayIsOn = true;
};
};

Related

How to add draw over an OpenLayer 3 map?

I am new to OpenLayers 3. I am trying to learn how to draw and save data over an OpenLayers map. Following an example, I am trying to learn about drawing and saving data. However, I am unable to draw anything over the map. I am posting the code below.
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<title>OpenLayers 3 example</title>
<script src="js/ol.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<div>
<label>Interaction type: </label>
<label>draw</label>
<input type="radio" id="interaction_type_draw" name="interaction_type" value="draw" checked>
<label>modify</label>
<input type="radio" id="interaction_type_modify" name="interaction_type" value="modify">
</div>
<div>
<label>Geometry type</label>
<select id="geom_type">
<option value="Point" selected>Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
</select>
</div>
<div>
<label>Data type</label>
<select id="data_type">
<option value="GeoJSON" selected>GeoJSON</option>
<option value="KML">KML</option>
<option value="GPX">GPX</option>
</select>
</div>
<div id="delete" style="text-decoration:underline;cursor:pointer">
Delete all features
</div>
<label>Data:</label>
<textarea id="data" rows="12" style="width:100%"></textarea>
<script>
var source = new ol.source.Vector();
var vector = new ol.layer.Vector({
source: source, style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)' }),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
// Create a map
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vector
],
view: new ol.View({
zoom: 2,
center: [0, 0]
})
});
// make draw global so it can later be removed
var draw;
// creat a select to choose geometry type
var typeSelect = document.getElementById('type');
// rebuild interaction when changed
typeSelect.onchange = function(e) {
map.removeInteraction(draw);
addInteraction();
};
// create a select to choose a data type to save in
dataTypeSelect = document.getElementById('data_type');
// clear map and rebuild interaction when changed
dataTypeSelect.onchange = function(e) {
clearMap();
map.removeInteraction(draw);
addInteraction();
};
// add draw interaction
function addInteraction() {
var geom_type = typeSelect.value;
if (geom_type !== 'None') {
draw = new ol.interaction.Draw({
source: source,
type: /** #type {ol.geom.GeometryType} */ (geom_type)
});
draw.on('drawend', function(evt) {
saveData();
});
map.addInteraction(draw);
}
}
function saveData() {
var allFeatures = vector.getSource().getFeatures(),
format = new ol.format[dataTypeSelect.value](),
data;
try {
data = format.writeFeatures(allFeatures);
} catch (e) {
// at time of creation there is an error in the GPX format (18.7.2014)
document.getElementById('data').value = e.name + ": " + e.message;
return;
}
if (dataTypeSelect.value === 'GeoJSON') {
// format is JSON
document.getElementById('data').value = JSON.stringify(data, null, 4);
} else {
// format is XML (GPX or KML)
var serializer = new XMLSerializer();
document.getElementById('data').value = serializer.serializeToString(data);
}
}
// add the interaction when the page is first shown
addInteraction();
// clear map when user clicks on 'Delete all features'
$("#delete").click(function() {
clearMap();
});
// clears the map and the output of the data
function clearMap() {
vector.getSource().clear();
document.getElementById('data').value = '';
}
</script>
</body>
</html>
Please tell me why am I not able to see any drawings over the map? However, the example that I am looking at works just fine. I am unable to find out the problem. Please help me out so that I can experiment with openLayers and learn more. Thanks!
You should be more careful about selecting dom elements using jquery. Also i strongly recommend using Firebug and checking the console for errors on page load. Here's the fixed full source.
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<title>OpenLayers 3 example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.17.1/ol-debug.js"></script>
<!--<script src="js/ol.js" type="text/javascript"></script>-->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<div>
<label>Interaction type: </label>
<label>draw</label>
<input type="radio" id="interaction_type_draw" name="interaction_type" value="draw" checked>
<label>modify</label>
<input type="radio" id="interaction_type_modify" name="interaction_type" value="modify">
</div>
<div>
<label>Geometry type</label>
<select id="geom_type">
<option value="Point" selected>Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
</select>
</div>
<div>
<label>Data type</label>
<select id="data_type">
<option value="GeoJSON" selected>GeoJSON</option>
<option value="KML">KML</option>
<option value="GPX">GPX</option>
</select>
</div>
<div id="delete" style="text-decoration:underline;cursor:pointer">
Delete all features
</div>
<label>Data:</label>
<textarea id="data" rows="12" style="width:100%"></textarea>
<script>
var source = new ol.source.Vector();
var vector = new ol.layer.Vector({
source: source, style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
// Create a map
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vector
],
view: new ol.View({
zoom: 2,
center: [0, 0]
})
});
// make draw global so it can later be removed
var draw;
// creat a select to choose geometry type
var typeSelect = document.getElementById('geom_type');
// rebuild interaction when changed
typeSelect.onchange = function (e) {
map.removeInteraction(draw);
addInteraction();
};
// create a select to choose a data type to save in
dataTypeSelect = document.getElementById('data_type');
// clear map and rebuild interaction when changed
dataTypeSelect.onchange = function (e) {
clearMap();
map.removeInteraction(draw);
addInteraction();
};
// add draw interaction
function addInteraction() {
var geom_type = typeSelect.value;
if (geom_type !== 'None') {
draw = new ol.interaction.Draw({
source: source,
type: /** #type {ol.geom.GeometryType} */ (geom_type)
});
draw.on('drawend', function (evt) {
saveData();
});
map.addInteraction(draw);
}
}
function saveData() {
var allFeatures = vector.getSource().getFeatures(),
format = new ol.format[dataTypeSelect.value](),
data;
try {
data = format.writeFeatures(allFeatures);
} catch (e) {
// at time of creation there is an error in the GPX format (18.7.2014)
document.getElementById('data').value = e.name + ": " + e.message;
return;
}
if (dataTypeSelect.value === 'GeoJSON') {
// format is JSON
document.getElementById('data').value = JSON.stringify(data, null, 4);
} else {
// format is XML (GPX or KML)
var serializer = new XMLSerializer();
document.getElementById('data').value = serializer.serializeToString(data);
}
}
// add the interaction when the page is first shown
addInteraction();
// clear map when user clicks on 'Delete all features'
$("#delete").click(function () {
clearMap();
});
// clears the map and the output of the data
function clearMap() {
vector.getSource().clear();
document.getElementById('data').value = '';
}
</script>
</body>
</html>

How to print a specific extent of an ArcGis Map?

I'm trying to print a specific zone on an Arcgis maps with the JS API (not the extend that is displayed).
I didn't find any method or option to do this so I tried to change the extend and then print the map :
var extent = new esri.geometry.Extent(
-620526.0922336339,
5993991.149960931,
108988.90572005256,
6293624.300838808,
myMap.spatialReference
);
myMap.setExtent(extent, true).then(function() {
console.log('setExtend is finished');
var template = new esri.tasks.PrintTemplate();
template.exportOptions = {
width : 500,
height : 500
};
template.format = 'jpg';
template.layout = 'MAP_ONLY';
var params = new esri.tasks.PrintParameters();
params.map = myMap;
params.template = template;
var printTask = new esri.tasks.PrintTask(urlToThePrintServer);
printTask.execute(params);
});
Since setExtent is asynchonous and return a defered I have to use the 'then' method.
I can see the map moving but the defered doesn't seem to works ... (I don't see the console.log()).
is there another way to print a specific extend of a map ?
if not why is the 'then' method never called ?
(I'm using the 3.12 JS API)
Your code looks good to me, though obviously you didn't post all your JavaScript or any of your HTML. Maybe you're not requiring the modules you need. Or maybe your code is trying to run before the map is loaded, though that's unlikely because as you say, the map does move. Or maybe something else is wrong.
I put a full working example at http://jsfiddle.net/06jtccx0/ . Hopefully you can compare that to what you're doing and figure out what is wrong with your code. Here's the same code for your convenience:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
<title>Simple Map</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.13/esri/css/esri.css">
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
body {
background-color: #FFF;
overflow: hidden;
font-family: "Trebuchet MS";
}
</style>
<script src="http://js.arcgis.com/3.13/"></script>
<script>
var myMap;
var urlToThePrintServer = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task";
require(["esri/map", "dojo/domReady!"], function(Map) {
myMap = new Map("map", {
basemap: "topo", //For full list of pre-defined basemaps, navigate to http://arcg.is/1JVo6Wd
center: [-122.45, 37.75], // longitude, latitude
zoom: 13
});
myMap.on("load", function(map) {
var extent = new esri.geometry.Extent(
-620526.0922336339,
5993991.149960931,
108988.90572005256,
6293624.300838808,
myMap.spatialReference
);
myMap.setExtent(extent, true).then(function() {
console.log('setExtend is finished');
require([
"esri/tasks/PrintTemplate",
"esri/tasks/PrintParameters",
"esri/tasks/PrintTask"
], function(
PrintTemplate,
PrintParameters,
PrintTask
) {
var template = new PrintTemplate();
template.exportOptions = {
width : 500,
height : 500
};
template.format = 'jpg';
template.layout = 'MAP_ONLY';
var params = new PrintParameters();
params.map = myMap;
params.template = template;
var printTask = new PrintTask(urlToThePrintServer);
printTask.execute(params, function(response) {
console.log("The printed document is at " + response.url);
window.open(response.url);
});
});
});
});
});
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

Web Component: How to listen to Shadow DOM load event?

I want to execute a JavaScript code on load of the Shadow DOM in my custom element.
I tried the following code but it did not work
x-component.html:
<template id="myTemplate">
<div>I am custom element</div>
</template>
<script>
var doc = this.document._currentScript.ownerDocument;
var XComponent = document.registerElement('x-component', {
prototype: Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var root = this.createShadowRoot();
var template = doc.querySelector('#myTemplate');
var clone = document.importNode(template.content, true);
clone.addEventListener('load', function(e) {
alert('Shadow DOM loaded!');
});
root.appendChild(clone);
}
}
})
});
</script>
Then I use it in another html as follows -
index.html:
<!doctype html>
<html >
<head>
<script src="bower_components/webcomponentsjs/webcomponents.min.js"></script>
<link rel="import" href="x-component.html">
</head>
<body>
<x-component></x-component>
</body>
</html>
The doc variable is used as I am using Polymer webcomponents.js polyfill and the polyfill needs it.
What is the right syntax to listen to load event of Shadow DOM?
AFAIK, the only way to achieve this is to use MutationObserver:
attachedCallback: {
value: function() {
var root = this.createShadowRoot();
var template = document.querySelector('#myTemplate');
var clone = document.importNode(template.content, true);
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.addedNodes) { // this is definitely a subject to change
alert('Shadow is loaded');
};
});
})
observer.observe(root, { childList: true });
root.appendChild(clone);
}
}
I would be glad to know if there is more elegant way, but for now I use this one.
Live preview: http://plnkr.co/edit/YBh5i2iCOwqpgsUU6En8?p=preview

Creating Waypoints using Bing Maps API

I'm creating a program that would allow users to save a route to a database - however, that's against the terms for Bing Maps, so I am allowing waypoints to be created and saved. I'm not quite sure how to start doing that. I thought I knew how to create the waypoints - but it's not working I'm using Visual Studio - VB.NET/ASP.NET. Would it be recommended to put it in through HTML or Visual Basic? HTML is where all the other Bing coding is located.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var directionsManager;
var directionsErrorEventObj;
var directionsUpdatedEventObj;
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), { credentials: 'AohjORMDA3Vf0mCtDaEsnVHlza-E9AQMlGa0fKhH-6cvoT09Wjhc2RVzCpKG9HbP' });
}
function createDirectionsManager() {
var displayMessage;
if (!directionsManager) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
displayMessage = 'Directions Module loaded\n';
displayMessage += 'Directions Manager loaded';
}
alert(displayMessage);
directionsManager.resetDirections();
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function (arg) { alert(arg.message) });
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () { alert('Directions updated') });
}
function createDrivingRoute() {
if (!directionsManager) { createDirectionsManager(); }
directionsManager.resetDirections();
// Set Route Mode to driving
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Bismarck, ND' });
directionsManager.addWaypoint(startWaypoint);
var destinationWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('hometown').value });
directionsManager.addWaypoint(destinationWaypoint);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
function createDirections() {
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute });
}
else {
createDrivingRoute();
}
}
function hometown_onclick() {
}
This is what I have as of right now. This is the code I need to put in for a waypoint - when I have tried putting it in, the directions did not show up:
function addWaypoint() {
if (!directionsManager) { createDirectionsManager(); }
if (directionsManager.getAllWaypoints().length < 2) {
directionsManager.resetDirections();
var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Bismarck, ND' });
directionsManager.addWaypoint(startWaypoint);
var destinationWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('hometown').value });
directionsManager.addWaypoint(destinationWaypoint);
}
// Insert a waypoint
directionsManager.addWaypoint(new Microsoft.Maps.Directions.Waypoint({ address: 'Mandan, ND' });
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
displayAlert('Calculating directions...');
directionsManager.calculateDirections();
}
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: addWaypoint });
}
else {
addWaypoint();
}
Let's start with this problem. How can I fix this?
I found the answer. The waypoint will load automatically once the form is loaded.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol /mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var directionsManager;
var directionsErrorEventObj;
var directionsUpdatedEventObj;
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), { credentials: 'AohjORMDA3Vf0mCtDaEsnVHlza-E9AQMlGa0fKhH-6cvoT09Wjhc2RVzCpKG9HbP' });
}
function createDirectionsManager() {
var displayMessage;
if (!directionsManager) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
displayMessage = 'Directions Module loaded\n';
displayMessage += 'Directions Manager loaded';
}
alert(displayMessage);
directionsManager.resetDirections();
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function (arg) { alert(arg.message) });
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () { alert('Directions updated') });
}
function createDrivingRoute() {
if (!directionsManager) { createDirectionsManager(); }
directionsManager.resetDirections();
// Set Route Mode to driving
{
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: '7500 University Dr., Bismarck, ND' });
directionsManager.addWaypoint(startWaypoint);
var destinationWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('hometown').value });
directionsManager.addWaypoint(destinationWaypoint);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
// Insert a waypoint
directionsManager.addWaypoint(new Microsoft.Maps.Directions.Waypoint({ address: 'Bismarck, ND'}), 1);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
function createDirections() {
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute });
}
else {
createDrivingRoute();
}
}

How to initialize a google maps on pageinit without repeatingly loading the google map api script

I would like to be able to load the Google.maps API only once for alle my pages.
Then i would like to be able to use geolocation or loading a map into a page anywhere on my web app.
The problem is that I cant figure out to seperate API loading and map initialization.
Which means i need to load the API each time I create a map.
I have referenced most of my code further down in the post but i suppose the following code is the problem.That piece of code takes care of the API Loading but at the same time it takes care of setting the initialize() function as a callback function and calling it.
var script = document.createElement("script");
script.type = "text/javascript";
script.src ="http://maps.googleapis.com/maps/api/js?key=mykey&sensor=false&callback=initialize";
document.body.appendChild(script);
How do i load the api once, lets say in the header, and then create a new map each time I go to specific page. WIthout loading the maps API again. (Note that im using Jquery mobile so my header only gets loaded one time for a session.)
I get this error:
Warning: you have included the Google Maps API multiple times on this page. This may cause unexpected errors.
Ii would like to tell you my setup.
-Im using Google Map APi v3
-I'm loading the API dynamically after the page has loaded.
-I'm using Jquery mobile, which means the page with google maps only gets partially reloaded when you visit it.
-Im using google maps for two things to show the map and for geolocation.
-I'm using the Google map api on several pages.
Im interacting with the map in 3 different places: In a header javascript see code below
A header javascript
A javascript in the body
The DIV in the body that holds the map.
Here is my code for the javascript that handles loading the API, showing the map, markers etc:
<script>
$('.error').hide();
//search criterias
var radius;
var timerange;
var type;
//user position variables
var userposition = false;
var mylatitudedegree = "=55.698";
var mylongitudedegree = "=12.579";
//map variables
var mapready = false;
var map;
var bound;
var markersArray = [];
//array for keeping track of the markers
var markercenter;
//hack
var pageinit = 0;
var initializer = 0;
var triggersearch = 0;
var loadscripts = 0;
var isgooglemapsloaded = false;
$( '#soegsagside' ).live( 'pageinit',function(event)
{
pageinit++;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition, function(error) {
alert('Din location er ikke tilgængelig! Error code: ' + error.code);
userposition = false;
}, {
maximumAge : 60000,
timeout : 10000,
enableHighAccuracy : true
});
}
else {
alert("Din browser tillader ikke, at vise din lokation!");
userposition = false;
}
loadScript();
$("#search_filter_button").click(function() {
//hide the "skal udfyldes" labels
$('.error').hide();
// validate and process form here
radius = $("select#choose_radius_select").val();
if (radius == "vælg") {
$("label#radius_error").show();
$("select#choose_radius_select").focus();
return false;
}
timerange = $("select#choose_timerange_select").val();
if (timerange == "vælg") {
$("label#timerange_error").show();
$("select#choose_timerange_select").focus();
return false;
}
type = $("select#vælg_type").val();
if (type == "vælg") {
$("label#select_type_error").show();
$("select#vælg_type").focus();
return false;
}
//------------------post to php script ---------------
var dataString = 'radius=' + radius + '&timerange=' + timerange + '&type=' + type + '&mylatitudedegree=' + mylatitudedegree + '&mylongitudedegree=' + mylongitudedegree;
$.ajax({
type : "POST",
url : "soegsagDB.php",
data : dataString,
success : function(data) {
$('#søgeresultater').html(data);
$('#søgeresultater').trigger('create');
clearOverlays();
createtaskmarkers();
findCenterOfMarkers();
if (userposition) {
usergeoposition = new google.maps.LatLng(mylatitudedegree, mylongitudedegree);
map.setCenter(usergeoposition);
createuserposition(usergeoposition);
} else {
map.setCenter(markercenter);
}
expandMapBoundForMarkers()
}
});
//end of post search query to server
return false;
});
//end of click seach button
});
//end of page ready
function setPosition(position) {
userposition = true;
myposition = position.coords;
mylatitudedegree = position.coords.latitude;
mylongitudedegree = position.coords.longitude;
var milli = new Date();
}
//function for clearing the markerArray
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
}
//Function for initializing the map, which is called when the map is created
function initialize() {
initializer++;
bound = new google.maps.LatLngBounds();
var mapOptions = {
zoom : 13,
center : new google.maps.LatLng(55, 12),
mapTypeId : google.maps.MapTypeId.ROADMAP
}
//Create a map
map = new google.maps.Map(document.getElementById("map"), mapOptions);
mapready = true;
$("#search_filter_button").trigger('click');//Trigger click on the search button
triggersearch++;
}
//create user positio marker
function createuserposition(usergeoposition) {
var userPositionMarker = new google.maps.Marker({
position : usergeoposition,
map : map,
title : "Din position",
});
markersArray.push(userPositionMarker);
}
function createtaskmarkers() {
//Create the markers of the tasks
//1. find the task <li> that contain the data and loop through each one
//2. for each task collect the dato into variables and create markers and infowindows
//3. calculate center of point
//4. extendt map area to contain all points
var data = $.map($('li'), function(element) {
if (element.hasAttribute("data-latitude")) {
var tempPos = new google.maps.LatLng($(element).attr('data-latitude'), $(element).attr('data-longitude'));
var link = $(element).attr('data-link');
var title = $(element).attr('data-title');
var type = $(element).attr('data-type');
var date = $(element).attr('data-date');
tempMarker = new google.maps.Marker({
position : tempPos,
map : map,
title : title,
});
tempMarker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
var tempContentString = '<div style="width: 200px; height: 100px;">' + date + '<br></br>' + '<b>' + type + ' , ' + title + '</b>' + '</div>';
//Create infowindow
var tempInfowindow = new google.maps.InfoWindow({
content : tempContentString
});
//add market to markerArray
markersArray.push(tempMarker);
//Create event with infowindow
google.maps.event.addListener(tempMarker, 'click', function() {
tempInfowindow.open(map, this);
});
}
});
}
function findCenterOfMarkers() {
//calculate center of markers and change mapcenter to that
var sumlatitude = 0;
var sumlongitude = 0;
for ( position = 0; position < markersArray.length; position++) {
sumlatitude += markersArray[position].getPosition().lat();
sumlongitude += markersArray[position].getPosition().lat();
}
avglatitude = sumlatitude / markersArray.length;
avglongitude = sumlongitude / markersArray.length;
markercenter = new google.maps.LatLng(avglatitude, avglongitude);
}
function expandMapBoundForMarkers() {
//Extend bounds for map to fit all markers into map
for (var i in markersArray) {
bound.extend(markersArray[i].getPosition());
}
map.fitBounds(bound);
}
//loads the google maps api with KEY and appends the script to the document body
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyC8wZ6RmFySy0DnWvrUaA-2OJqcM1_AOIc&sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
The only thing in the body of the page that has to do with the maps. Is the DIV that the map is loaded into.
<div id="map" style="width: 80%; height: 280px; margin: auto; background-color: gray">Kortet loader, vent venligst.</div> <!--alternative for full screen style="position:absolute;top:30px;bottom:50px;left:0;right:0;"-->
The API is also loaded in a common header script. Because I in general need to load it on other pages.
<script src='http://maps.google.com/maps/api/js?sensor=false'></script>
<script type="text/javascript">
$(document).ready( function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=mynamespace.init_google_maps";
document.body.appendChild(script);
$(document).bind('pageinit', function() {
//do stuff here that happens each time a new page is loaded
});
});
});
</script>
the api is loaded once inside .ready(). you can create a new map in the callback that was passed to .bind() which is called each time a new page loads or is inserted. you can initialize the map inside mynamespace. mynamespace is a .js file included on the page