Google Maps in responsive tabs - javascript

I'm trying to add 3 Google maps in 3 responsive tabs but only the first one works:
I've tried many different solutions, including giving a number to the width to define the map size, instead of auto, but same results.
For what I understood is I need to tell the script to resize when changing tabs with something like this:
google.maps.event.trigger(map, 'resize');
but i don't know how. Can any one help please.
If I manually resize the window, the map will show
One more thing in Dw when i have a syntax error, the page actually works in the live preview, but not if i save. Just thought i should mention it.
function initialize() {
var myLatlngOH = new google.maps.LatLng(39.630159,-84.175937);
var myLatlngCA = new google.maps.LatLng(33.677705,-117.852974);
var myLatlngUK = new google.maps.LatLng(51.520614,-0.121825);
var mapOptionsOH = {
zoom: 5,
center: myLatlngOH,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: 1
}
var mapOptionsCA = {
zoom: 5,
center: myLatlngCA,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: 1
}
var mapOptionsUK = {
zoom: 5,
center: myLatlngUK,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: 1
}
var mapOH = new google.maps.Map(document.getElementById('map-OH'), mapOptionsOH);
var mapCA = new google.maps.Map(document.getElementById('map-CA'), mapOptionsCA);
var mapUK = new google.maps.Map(document.getElementById('map-UK'), mapOptionsUK);
var markerOH = new google.maps.Marker({
position: myLatlngOH,
map: mapOH,
title: 'Company Office - Ohio'
});
var markerCA = new google.maps.Marker({
position: myLatlngCA,
map: mapCA,
title: 'Company Office - California'
});
var markerUK = new google.maps.Marker({
position: myLatlngUK,
map: mapUK,
title: 'Company Office - London'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
(function() {
'use strict';
/**
* tabs
*
* #description The Tabs component.
* #param {Object} options The options hash
*/
var tabs = function(options) {
var el = document.querySelector(options.el);
var tabNavigationLinks = el.querySelectorAll(options.tabNavigationLinks);
var tabContentContainers = el.querySelectorAll(options.tabContentContainers);
var activeIndex = 0;
var initCalled = false;
/**
* init
*
* #description Initializes the component by removing the no-js class from
* the component, and attaching event listeners to each of the nav items.
* Returns nothing.
*/
var init = function() {
if (!initCalled) {
initCalled = true;
el.classList.remove('no-js');
for (var i = 0; i < tabNavigationLinks.length; i++) {
var link = tabNavigationLinks[i];
handleClick(link, i);
}
}
};
/**
* handleClick
*
* #description Handles click event listeners on each of the links in the
* tab navigation. Returns nothing.
* #param {HTMLElement} link The link to listen for events on
* #param {Number} index The index of that link
*/
var handleClick = function(link, index) {
link.addEventListener('click', function(e) {
e.preventDefault();
goToTab(index);
});
};
/**
* goToTab
*
* #description Goes to a specific tab based on index. Returns nothing.
* #param {Number} index The index of the tab to go to
*/
var goToTab = function(index) {
if (index !== activeIndex && index >= 0 && index <= tabNavigationLinks.length) {
tabNavigationLinks[activeIndex].classList.remove('is-active');
tabNavigationLinks[index].classList.add('is-active');
tabContentContainers[activeIndex].classList.remove('is-active');
tabContentContainers[index].classList.add('is-active');
activeIndex = index;
}
};
/**
* Returns init and goToTab
*/
return {
init: init,
goToTab: goToTab
};
};
/**
* Attach to global namespace
*/
window.tabs = tabs;
})();
var myTabs = tabs({
el: '#tabs',
tabNavigationLinks: '.c-tabs-nav__link',
tabContentContainers: '.c-tab'
});
myTabs.init();
#map-OH, #map-CA, #map-UK {
width: auto;
height: 600PX;
}
.c-tabs-nav {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
list-style: none;
margin: 0;
padding: 0;
}
.c-tabs-nav__link {
-webkit-box-flex: 1;
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
margin-right: 4px;
/* padding: 12px; */
color: #fff;
background-color: #b3b3b3;
text-align: center;
-webkit-transition: color 0.3s;
transition: color 0.3s;
}
.c-tab {
display: none;
}
.c-tab.is-active {
display: block;
}
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link href="style.css" rel="stylesheet" type="text/css">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=3.0" name="viewport">
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyC-5CY9mOCeg5Y3IhPqi_Yd0-DZtWrJl-E'></script>
<title></title>
</head>
<body>
<div class="c-tabs no-js" id="tabs">
<div class="c-tabs-nav">
<a class="c-tabs-nav__link is-active" href="#">
<p>Mappa</p></a> <a class="c-tabs-nav__link" href="#">
<p>Navi</p></a> <a class="c-tabs-nav__link" href="#">
<p>Streat</p></a>
</div>
<div class="c-tab is-active">
<div class="c-tab__content">
<div class="masked location-image pull-right" id="map-OH"></div>
</div>
</div>
<div class="c-tab">
<div class="c-tab__content">
<div class="masked location-image pull-right" id="map-CA"></div>
</div>
</div>
<div class="c-tab">
<div class="c-tab__content">
<div class="masked location-image pull-right" id="map-UK"></div>
</div>
</div>
</div>
<script src="tabs.js">
</script>
</body>
</html>

Didn't solve it, but i used iframe instead of the javascript, and it works in all 3 tabs

Related

How can I compute current speed, average speed and total distance with leafletjs?

I have a tracking map using Leaflet.js and I want to display:
a) current speed,
b) average speed and
c) total distance traveled.
How would I do this? https://jsfiddle.net/chovy/rfvtwed5/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/#turf/turf#6/turf.min.js"></script>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""
/>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css"
/>
<style>
html {
font-size: 62.5%;
}
body {
margin: 0;
padding: 0;
font-size: 1.6rem;
font-family: sans-serif;
width: 95vw;
height: 90vh;
margin: 0 auto;
}
header {
padding: 1rem 0;
}
#map {
width: 100%;
height: 100%;
}
.marker img {
width: 3rem;
}
.marker span {
display: block;
background: #fff;
width: 10rem;
padding: 1rem;
border-radius: 0.4rem;
border: 1px solid black;
}
#media (max-width: 481px) {
/* portrait e-readers (Nook/Kindle), smaller tablets # 600 or # 640 wide. */
#status {
display: block;
}
}
</style>
</head>
<body>
<header>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="marker">add marker</button>
<button id="export">export</button>
<span id="status"></span>
</header>
<div id="map"></div>
<script
src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""
></script>
<script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>
<script>
const exportButton = document.getElementById("export");
let intv;
const status = document.getElementById("status");
var map = L.map("map", {
center: [9.082, 8.6753],
zoom: 8,
});
var osm = L.tileLayer(
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
{
attribution:
'© SkateSpot, Inc.',
}
).addTo(map);
L.Control.geocoder().addTo(map);
if (!navigator.geolocation) {
console.log("Your browser doesn't support geolocation feature!");
}
const trackingPath = [];
const polyline = L.polyline([], {
color: "red",
weight: 3,
className: "path",
}).addTo(map);
function start() {
navigator.geolocation.getCurrentPosition(getPosition);
intv = setInterval(() => {
navigator.geolocation.getCurrentPosition(getPosition);
}, 1000);
}
function getPosition(position) {
// console.log(position)
const { latitude, longitude, accuracy } = position.coords;
const pos = [latitude, longitude];
//const pos = turf.randomPosition([49, 23, 43, 20])
trackingPath.push(pos);
polyline.addLatLng(pos);
map.fitBounds(polyline.getBounds());
console.log(
"Your coordinate is: Lat: " +
latitude +
" Long: " +
longitude +
" Accuracy: " +
accuracy
);
}
exportButton.addEventListener("click", function () {
console.log("trackingPath", trackingPath);
save("data.txt", JSON.stringify(trackingPath));
});
function save(filename, data) {
const blob = new Blob([data], { type: "text/csv" });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
const elem = window.document.createElement("a");
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
function addMarker(e) {
e.preventDefault();
console.log("add marker");
status.innerText = "adding marker...";
navigator.geolocation.getCurrentPosition((position) => {
const { latitude, longitude, accuracy } = position.coords;
const pos = [latitude, longitude];
var marker = L.marker(pos, {
icon: new L.DivIcon({
className: "marker",
html: `<img src="/marker.svg" alt="" />
<span contenteditable>click to edit</span>`,
}),
}).addTo(map);
var Overlaymaps = {
Marker: marker,
};
L.control.layers(Overlaymaps).addTo(map);
status.innerText = `Marker added at ${pos.join(", ")}`;
});
}
function startTracking(e) {
status.innerText = "Started tracking...";
e.preventDefault();
start();
}
function stopTracking(e) {
status.innerText = "Stopped tracking.";
e.preventDefault();
clearInterval(intv);
}
document.getElementById("start").addEventListener("click", startTracking);
document.getElementById("stop").addEventListener("click", stopTracking);
document.getElementById("marker").addEventListener("click", addMarker);
</script>
</body>
</html>
I'm just guessing here but I think for "current speed" I'd have to take the last 2 readings (every 1 second) and calculate distance and time passed to get speed. as for average speed I'd just take the first and the last data points and do the same.
Total distance I'd have to add up all the data points I assume since a path is not always a straight line.
I just have no idea how to do all this using gps coordinates.
Leaflet provides a useful latlngA.distanceTo(latlngB) method to convert a pair of GPS coordinates into actual distance:
Returns the distance (in meters) to the given LatLng calculated using the Spherical Law of Cosines.
With this, you can do something like:
let totalElapsedTime = 0;
let totalDistance = 0;
let previousTime;
let previousLatLng;
function getPosition(position) {
const currentTime = new Date();
const currentLatLng = L.latLng(
position.coords.latitude,
position.coords.longitude
);
// Skip first point (no computation is possible)
if (previousTime && previousLatLng) {
const elapsedTime = (currentTime.getTime() - previousTime.getTime()) / 1000; // In seconds
const distance = previousLatLng.distanceTo(currentLatLng);
const currentSpeed = distance / elapsedTime; // In meters / second
totalElapsedTime += elapsedTime;
totalDistance += distance;
const averageSpeed = totalDistance / totalElapsedTime; // In meters / second
}
// Record time and position for next computation
previousTime = currentTime;
previousLatLng = currentLatLng;
// Graphic stuff...
}
Note: for average speed you also need total travelled distance to account for non straight line path, unless you want to compute "flying distance" irrespective of actual path, which can therefore decrease back to 0 in case the path becomes a loop back to starting point.

How do I add a label to the country name in Google Maps?

I am looking to add a small label near each of the countries name that will show it's population (e.g. Brazil [200,0000] ). Is there a way to do this with Google maps JS api?
My current code for map initialization:
// Define options
var options = {
center: {
lat: 48.1250223,
lng: 4.1264001
},
zoom: 3
};
// Init map
map = new google.maps.Map( $container.get(0), options );
Any help would be appreciated!
Data for the population is not available in the Google Maps API v3.
You will need to import data from an external source.
You can check this example from Google API https://developers.google.com/maps/documentation/javascript/combining-data
Full code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Mashups with google.maps.Data</title>
<style>
html, body, #map { height: 100%; margin: 0; padding: 0; overflow: hidden; }
.nicebox {
position: absolute;
text-align: center;
font-family: "Roboto", "Arial", sans-serif;
font-size: 13px;
z-index: 5;
box-shadow: 0 4px 6px -4px #333;
padding: 5px 10px;
background: rgb(255,255,255);
background: linear-gradient(to bottom,rgba(255,255,255,1) 0%,rgba(245,245,245,1) 100%);
border: rgb(229, 229, 229) 1px solid;
}
#controls {
top: 10px;
left: 110px;
width: 360px;
height: 45px;
}
#data-box {
top: 10px;
left: 500px;
height: 45px;
line-height: 45px;
display: none;
}
#census-variable {
width: 360px;
height: 20px;
}
#legend { display: flex; display: -webkit-box; padding-top: 7px }
.color-key {
background: linear-gradient(to right,
hsl(5, 69%, 54%) 0%,
hsl(29, 71%, 51%) 17%,
hsl(54, 74%, 47%) 33%,
hsl(78, 76%, 44%) 50%,
hsl(102, 78%, 41%) 67%,
hsl(127, 81%, 37%) 83%,
hsl(151, 83%, 34%) 100%);
flex: 1;
-webkit-box-flex: 1;
margin: 0 5px;
text-align: left;
font-size: 1.0em;
line-height: 1.0em;
}
#data-value { font-size: 2.0em; font-weight: bold }
#data-label { font-size: 2.0em; font-weight: normal; padding-right: 10px; }
#data-label:after { content: ':' }
#data-caret { margin-left: -5px; display: none; font-size: 14px; width: 14px}
</style>
</head>
<body>
<div id="controls" class="nicebox">
<div>
<select id="census-variable">
<option value="https://storage.googleapis.com/mapsdevsite/json/DP02_0066PE">Percent of population over 25 that completed high
school</option>
<option value="https://storage.googleapis.com/mapsdevsite/json/DP05_0017E">Median age</option>
<option value="https://storage.googleapis.com/mapsdevsite/json/DP05_0001E">Total population</option>
<option value="https://storage.googleapis.com/mapsdevsite/json/DP02_0016E">Average family size</option>
<option value="https://storage.googleapis.com/mapsdevsite/json/DP03_0088E">Per-capita income</option>
</select>
</div>
<div id="legend">
<div id="census-min">min</div>
<div class="color-key"><span id="data-caret">◆</span></div>
<div id="census-max">max</div>
</div>
</div>
<div id="data-box" class="nicebox">
<label id="data-label" for="data-value"></label>
<span id="data-value"></span>
</div>
<div id="map"></div>
<script>
var mapStyle = [{
'stylers': [{'visibility': 'off'}]
}, {
'featureType': 'landscape',
'elementType': 'geometry',
'stylers': [{'visibility': 'on'}, {'color': '#fcfcfc'}]
}, {
'featureType': 'water',
'elementType': 'geometry',
'stylers': [{'visibility': 'on'}, {'color': '#bfd4ff'}]
}];
var map;
var censusMin = Number.MAX_VALUE, censusMax = -Number.MAX_VALUE;
function initMap() {
// load the map
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40, lng: -100},
zoom: 4,
styles: mapStyle
});
// set up the style rules and events for google.maps.Data
map.data.setStyle(styleFeature);
map.data.addListener('mouseover', mouseInToRegion);
map.data.addListener('mouseout', mouseOutOfRegion);
// wire up the button
var selectBox = document.getElementById('census-variable');
google.maps.event.addDomListener(selectBox, 'change', function() {
clearCensusData();
loadCensusData(selectBox.options[selectBox.selectedIndex].value);
});
// state polygons only need to be loaded once, do them now
loadMapShapes();
}
/** Loads the state boundary polygons from a GeoJSON source. */
function loadMapShapes() {
// load US state outline polygons from a GeoJson file
map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/states.js', { idPropertyName: 'STATE' });
// wait for the request to complete by listening for the first feature to be
// added
google.maps.event.addListenerOnce(map.data, 'addfeature', function() {
google.maps.event.trigger(document.getElementById('census-variable'),
'change');
});
}
/**
* Loads the census data from a simulated API call to the US Census API.
*
* #param {string} variable
*/
function loadCensusData(variable) {
// load the requested variable from the census API (using local copies)
var xhr = new XMLHttpRequest();
xhr.open('GET', variable + '.json');
xhr.onload = function() {
var censusData = JSON.parse(xhr.responseText);
censusData.shift(); // the first row contains column names
censusData.forEach(function(row) {
var censusVariable = parseFloat(row[0]);
var stateId = row[1];
// keep track of min and max values
if (censusVariable < censusMin) {
censusMin = censusVariable;
}
if (censusVariable > censusMax) {
censusMax = censusVariable;
}
// update the existing row with the new data
map.data
.getFeatureById(stateId)
.setProperty('census_variable', censusVariable);
});
// update and display the legend
document.getElementById('census-min').textContent =
censusMin.toLocaleString();
document.getElementById('census-max').textContent =
censusMax.toLocaleString();
};
xhr.send();
}
/** Removes census data from each shape on the map and resets the UI. */
function clearCensusData() {
censusMin = Number.MAX_VALUE;
censusMax = -Number.MAX_VALUE;
map.data.forEach(function(row) {
row.setProperty('census_variable', undefined);
});
document.getElementById('data-box').style.display = 'none';
document.getElementById('data-caret').style.display = 'none';
}
/**
* Applies a gradient style based on the 'census_variable' column.
* This is the callback passed to data.setStyle() and is called for each row in
* the data set. Check out the docs for Data.StylingFunction.
*
* #param {google.maps.Data.Feature} feature
*/
function styleFeature(feature) {
var low = [5, 69, 54]; // color of smallest datum
var high = [151, 83, 34]; // color of largest datum
// delta represents where the value sits between the min and max
var delta = (feature.getProperty('census_variable') - censusMin) /
(censusMax - censusMin);
var color = [];
for (var i = 0; i < 3; i++) {
// calculate an integer color based on the delta
color[i] = (high[i] - low[i]) * delta + low[i];
}
// determine whether to show this shape or not
var showRow = true;
if (feature.getProperty('census_variable') == null ||
isNaN(feature.getProperty('census_variable'))) {
showRow = false;
}
var outlineWeight = 0.5, zIndex = 1;
if (feature.getProperty('state') === 'hover') {
outlineWeight = zIndex = 2;
}
return {
strokeWeight: outlineWeight,
strokeColor: '#fff',
zIndex: zIndex,
fillColor: 'hsl(' + color[0] + ',' + color[1] + '%,' + color[2] + '%)',
fillOpacity: 0.75,
visible: showRow
};
}
/**
* Responds to the mouse-in event on a map shape (state).
*
* #param {?google.maps.MouseEvent} e
*/
function mouseInToRegion(e) {
// set the hover state so the setStyle function can change the border
e.feature.setProperty('state', 'hover');
var percent = (e.feature.getProperty('census_variable') - censusMin) /
(censusMax - censusMin) * 100;
// update the label
document.getElementById('data-label').textContent =
e.feature.getProperty('NAME');
document.getElementById('data-value').textContent =
e.feature.getProperty('census_variable').toLocaleString();
document.getElementById('data-box').style.display = 'block';
document.getElementById('data-caret').style.display = 'block';
document.getElementById('data-caret').style.paddingLeft = percent + '%';
}
/**
* Responds to the mouse-out event on a map shape (state).
*
* #param {?google.maps.MouseEvent} e
*/
function mouseOutOfRegion(e) {
// reset the hover state, returning the border to normal
e.feature.setProperty('state', 'normal');
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
</body>
</html>
You could use the label of a marker without displaying the marker. Attached a short example. Mmmmh, or use the country flag as icon and show the label over it.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Marker with Label</title>
<style>
#map {height: 100%;}
html, body {height: 100%;}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 48.1, lng: 4.1},
mapTypeId: 'terrain'
});
//set the text as marker label without displayinge the marker
var m = new google.maps.Marker({
position: {lat: 48.1, lng: 4.1},
label: {
color: 'purple',
fontWeight: 'bold',
text: 'people: 67 Mio',
},
icon: {
url: 'none_marker.png',
anchor: new google.maps.Point(10, -25),
},
map: map
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
</body>
</html>

issue with click event in nokia maps api

i try this code
for(i=0; i<num ;i++)
{
points.push([lats[i], lngs[i]]);
if(i==0) str = 'S';
else if(i==num-1) str = 'E';
else str = '';
var marker = new nokia.maps.map.Marker(
[lats[i], lngs[i]],
{
title: str,
visibility: true,
icon: img,
anchor: new nokia.maps.util.Point(5, 5)
});
marker.addListener('click', function(evt){
$('.loc').html(times[i]);
});
map.objects.add(marker);
}
but it just does not fire click event. is anything wrong with code?
lats and lngs and times are defined and points is to be used later.
Edit:
Problem solved. See comment for answer below.
It looks like the problem is with the line:
$('.loc').html(times[i]);
Within the marker listener. The event hasn't got access to the array element when it is fired and therefore fails. I think you need to add an attribute to the marker and access it as shown:
var marker = new nokia.maps.map.Marker(
[lats[i], lngs[i]],
{
title: str,
visibility: true,
icon: img,
anchor: new nokia.maps.util.Point(29, 71),
$html : times[i]
});
marker.addListener('click', function(evt){
//$('.loc').html(times[i]);
alert (evt.target.$html);
});
Try the following (with your own App Id and token of course):
<!DOCTYPE HTML SYSTEM>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9" />
<script type="text/javascript" charset="UTF-8" src="http://api.maps.nokia.com/2.2.3/jsl.js"></script>
<style type="text/css">
html {
overflow:hidden;
}
body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%;
position: absolute;
}
#mapContainer {
width:100%;
height: 100%;
left: 0;
top: 0;
position: absolute;
}
</style>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript">
nokia.Settings.set( "appId", "YOUR APP ID GOES HERE");
nokia.Settings.set( "authenticationToken", "YOUR AUTHENTICATION TOKEN GOES HERE");
var mapContainer = document.getElementById("mapContainer");
var DefaultLatitude = 52.516237;
var DefaultLongitude = 13.377686;
var defaultZoomLevel = 16;
var mapOptions =
{
baseMapType: nokia.maps.map.Display.NORMAL,
center: new nokia.maps.geo.Coordinate(DefaultLatitude, DefaultLongitude),
zoomLevel: defaultZoomLevel,
components: [
new nokia.maps.map.component.ZoomBar(),
new nokia.maps.map.component.Behavior(),
new nokia.maps.map.component.Overview(),
new nokia.maps.map.component.ScaleBar(),
new nokia.maps.map.component.ContextMenu()
]
};
var map = new nokia.maps.map.Display(mapContainer, mapOptions);
var str ="";
var img = "http://api.maps.nokia.com/en/playground/examples/maps/res/markerHouse.png";
var points= new Array();
var lats = new Array();
var lngs = new Array();
var times = new Array();
var num;
lats[0] = 52.516237;
lngs[0] = 13.377686;
times[0] = "brandenburg gate";
num = 1;
for(var i=0; i<num ;i++)
{
points.push([lats[i], lngs[i]]);
if(i==0) str = 'S';
else if(i==num-1) str = 'E';
else str = '';
var marker = new nokia.maps.map.Marker(
[lats[i], lngs[i]],
{
title: str,
visibility: true,
icon: img,
anchor: new nokia.maps.util.Point(29, 71),
$html : times[i]
});
marker.addListener('click', function(evt){
//$('.loc').html(times[i]);
alert (evt.target.$html);
});
map.objects.add(marker);
}
</script>
</body>
</html>

Openlayers - display pacific markers popup using marker id and onclick event

I have the following code which addes 3 markers to the map along with there popup boxes what I want to do is have a list of location at bottom of page and using the id of the marker when click a place in the list it just make that places popup appear on the map.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Open Street Map</title>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 100%; height: 100%; border: 0px; padding: 0px; }
</style>
<script src="lib/OpenLayers.js" type="text/javascript"></script>
<script type="text/javascript">
var iconSize = new OpenLayers.Size(21, 25);
var iconOffset = new OpenLayers.Pixel(-(iconSize.w / 2), -iconSize.h);
var icon = new OpenLayers.Icon("img/fourmarker.png",
iconSize, iconOffset);
var zoom, center, currentPopup, map, lyrMarkers;
var popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
"autoSize": true,
"minSize": new OpenLayers.Size(300, 50),
"maxSize": new OpenLayers.Size(500, 300),
"keepInMap": true
});
var bounds = new OpenLayers.Bounds();
function addMarker(id, lng, lat, info) {
var pt = new OpenLayers.LonLat(lng, lat)
.transform(new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject());
bounds.extend(pt);
var feature = new OpenLayers.Feature(lyrMarkers, pt);
feature.closeBox = true;
feature.popupClass = popupClass;
feature.data.popupContentHTML = info ;
feature.data.overflow = "auto";
var marker = new OpenLayers.Marker(pt, icon.clone());
var markerClick = function(evt) {
if (currentPopup != null && currentPopup.visible()) {
currentPopup.hide();
}
if (this.popup == null) {
this.popup = this.createPopup(this.closeBox);
map.addPopup(this.popup);
this.popup.show();
} else {
this.popup.toggle();
}
currentPopup = this.popup;
OpenLayers.Event.stop(evt);
};
marker.events.register("mousedown", feature, markerClick);
lyrMarkers.addMarker(marker);
}
function initMap() {
var options = {
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
units: "m",
numZoomLevels: 19,
maxResolution: 156543.0339,
maxExtent: new OpenLayers.Bounds(-0.13011, -0.13011, 51.51039, 51.51039)
};
map = new OpenLayers.Map("map", options);
map.addControl(new OpenLayers.Control.DragPan());
var lyrOsm = new OpenLayers.Layer.OSM();
map.addLayer(lyrOsm);
lyrMarkers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(lyrMarkers);
//add marker on given coordinates
addMarker('1',-0.12519,51.51112 , '<b>Tescos</b><br/>Covent garden');
addMarker('2',-0.13264,51.50918 , '<b>Spar</b><br/>Leicester Square');
addMarker('3', -0.12498,51.50807 , '<b>M & S</b><br/>Embankment');
center = bounds.getCenterLonLat();
map.setCenter(center, map.getZoomForExtent(bounds) - 1);
zoom = map.getZoom();
}
</script>
</head>
<body onload="initMap()" style="margin:0; border:0; padding:0; width:1000px; height:500px;">
<div id="map"></div>
</body>
</html>
EXTRA INFORMATION
I am going to add a list to bottom of map like so:
<ul>
<li>location1</li>
<li>location2</li>
<li>location3</li>
</ul>
What i want to get working is when the user clicks so location1 alink then that relevent popup box will show and the other will be removed.
How would this be done.
This very fast example (modify addMarker function):
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Open Street Map</title>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 100%; height: 100%; border: 0px; padding: 0px; }
#list > div { background-color: #aaa; margin-top: 10px; }
</style>
<script src="http://openlayers.org/api/OpenLayers.js" type="text/javascript"> </script>
</head>
<body onload="initMap()" style="margin:0; border:0; padding:0; width:1000px; height:500px;">
<div id="map"></div>
<div id="list" style="width:100%; height: 100%"></div>
</body>
<script type="text/javascript">
var iconSize = new OpenLayers.Size(21, 25);
var iconOffset = new OpenLayers.Pixel(-(iconSize.w / 2), -iconSize.h);
var icon = new OpenLayers.Icon("img/fourmarker.png",
iconSize, iconOffset);
var list = document.getElementById('list');
var zoom, center, currentPopup, map, lyrMarkers;
var popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
"autoSize": true,
"minSize": new OpenLayers.Size(300, 50),
"maxSize": new OpenLayers.Size(500, 300),
"keepInMap": true
});
var bounds = new OpenLayers.Bounds();
function addMarker(id, lng, lat, info) {
var pt = new OpenLayers.LonLat(lng, lat)
.transform(new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject());
bounds.extend(pt);
var feature = new OpenLayers.Feature(lyrMarkers, pt);
feature.closeBox = true;
feature.popupClass = popupClass;
feature.data.popupContentHTML = info ;
feature.data.overflow = "auto";
var marker = new OpenLayers.Marker(pt, icon.clone());
var markerClick = function(evt) {
if (currentPopup != null && currentPopup.visible()) {
currentPopup.hide();
}
if (this.popup == null) {
this.popup = this.createPopup(this.closeBox);
map.addPopup(this.popup);
this.popup.show();
} else {
this.popup.toggle();
}
currentPopup = this.popup;
OpenLayers.Event.stop(evt);
};
marker.events.register("mousedown", feature, markerClick);
lyrMarkers.addMarker(marker);
// add items
var listItem = OpenLayers.Util.createDiv(this.id, null, null, null, 'relative', null);
listItem.innerHTML = info;
list.appendChild(listItem);
var callback = function(e) {
marker.events.triggerEvent('mousedown');
console.log(marker);
OpenLayers.Event.stop(e);
};
OpenLayers.Event.observe(listItem, "touchend", OpenLayers.Function.bindAsEventListener(callback, this));
OpenLayers.Event.observe(listItem, "click", OpenLayers.Function.bindAsEventListener(callback, this));
}
function initMap() {
var options = {
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
units: "m",
numZoomLevels: 19,
maxResolution: 156543.0339,
maxExtent: new OpenLayers.Bounds(-0.13011, -0.13011, 51.51039, 51.51039)
};
map = new OpenLayers.Map("map", options);
map.addControl(new OpenLayers.Control.DragPan());
var lyrOsm = new OpenLayers.Layer.OSM();
map.addLayer(lyrOsm);
lyrMarkers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(lyrMarkers);
//add marker on given coordinates
addMarker('1',-0.12519,51.51112 , '<b>Tescos</b><br/>Covent garden');
addMarker('2',-0.13264,51.50918 , '<b>Spar</b><br/>Leicester Square');
addMarker('3', -0.12498,51.50807 , '<b>M & S</b><br/>Embankment');
center = bounds.getCenterLonLat();
map.setCenter(center, map.getZoomForExtent(bounds) - 1);
zoom = map.getZoom();
}
</script>
</html>

how to pan two maps simultaneously overlay using div

I am having two maps which are overlayed using div. However whenever I pan the map, only the map above the base map moves and not the base map. Kindly tell if there is some way to let the mouse panning enabled for both the maps simultaneously.
Thanks
Astha
<style type='text/css'>
/*<![CDATA[*/
.modal {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.overlay {
margin: auto;
text-align: left;
width: 800px;
height: 532px;
position:absolute;
pointer-events:none;
}
.message {
width: 800px;
height: 532px;
background-color: #fff;
opacity: .35;
filter: alpha(opacity=35);
position:absolute;
pointer-events:none;
}
/*]]>*/
</style>
<script type="text/javascript" src="http://nls.tileserver.com/api.js"></script>
<script src="http://maps.google.com/maps? file=api&v=2&sensor=false&key=ABQIAAAA9pSslyaYyyl6x8HKrHAZvxS4-alJFZ9Cxp3qiYSlGHIYxF9uHhT0NLb9B9BXGUGGDctSO4QVa1jLLA" type="text/javascript">
</script>
<script src="http://nls.tileserver.com/opacity-control.js" type="text/javascript"> </script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script language="javascript">
function whereami(lat, lon) {
load(lat,lon);
}
/*
function pull() {
var location=JSON.parse(locater.getLocation());
whereami(location.lat, location.lon);
}*/
function load(latitude,longitude)
{
if (GBrowserIsCompatible()) {
//var latitude = 55.96;
//var longitude = -3.2;
var MyIcon = new GIcon();
var zoom = 18;
var map = new GMap(document.getElementById("map"));
map.setCenter(new GLatLng(latitude,longitude), zoom);
var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180),new GLatLng(90, 180)), 1,
"Historical maps from <a href='http://geo.nls.uk/maps/api/'>NLS Maps API<\/a>");
var copyrightCollection = new GCopyrightCollection();
copyrightCollection.addCopyright(copyright);
var tilelayer = new GTileLayer(copyrightCollection, 1, NLSTileUrlOS('MAXZOOM'));
tilelayer.getTileUrl = NLSTileUrlOS;
var nlsmap = new GMapType([tilelayer], G_NORMAL_MAP.getProjection(), "Historical");
map.addMapType(nlsmap);
map.setMapType(nlsmap);
var map1 = new GMap(document.getElementById("map1"));
map1.setCenter(new GLatLng(latitude,longitude), zoom);
var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180),new GLatLng(90, 180)), 1,
"Historical maps from <a href='http://geo.nls.uk/maps/api/'>NLS Maps API<\/a>");
var copyrightCollection = new GCopyrightCollection();
copyrightCollection.addCopyright(copyright);
var tilelayer = new GTileLayer(copyrightCollection, 1, NLSTileUrlOS('MAXZOOM'));
tilelayer.getTileUrl = NLSTileUrlOS;
var nlsmap = new GMapType([tilelayer], G_NORMAL_MAP.getProjection(), "Historical");
map1.addMapType(nlsmap);
map1.setMapType(nlsmap);
// put div over map
Position.clone($("map"), $("map1").setStyle({'pointer-events': 'none'}), {offsetLeft:100, offsetTop:62.5, setWidth:false, setHeight:false});
var marker = new GMarker( new GLatLng(latitude,longitude));
var myIcon=new GIcon(marker.getIcon());
myIcon.image='pushpin.png';
myIcon.iconSize = new GSize (40,40);
var marker2 = new GMarker( new GLatLng(latitude,longitude), myIcon);
map.addOverlay(marker2);
}
}
</script >
</head>
<body onload = whereami(55.96,-3.2)>
<div class="modal">
<div class="overlay" id="map">
</div>
<div class="message" id="map1"></div>
</div>
Probably u can use getCenter from map 1 and use latlang to setCenter of second on events u are moving mouse

Categories

Resources