how to pan two maps simultaneously overlay using div - javascript

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

Related

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>

Google Maps in responsive tabs

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

Google maps listener event acts like a click even though it is a mouseover

I am adding these two google.maps.event.addListener events
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
markerIconAcademicCenter.url = 'MapIcons/Circle32.png'
});
google.maps.event.addListener(markerAcademicCenter, "mouseout", function (e) {
markerIconAcademicCenter.url = 'MapIcons/Circle64.png'
});
below this marker that already has a click event.
google.maps.event.addListener(markerAcademicCenter, "click", function (e) {
$(".campusMapInfoPanel > div").appendTo($(".InfoStorageDiv"));
$(".InfoPanelAcademicCenter").appendTo($(".campusMapInfoPanel"));
this.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
setZoomWhenMarkerClicked();
CampusMap.setCenter(markerAcademicCenter.getPosition());
});
The markerIconAcademicCenter.url is already set to Circle64 above these events. I expect the page to load with the larger circle — 64x64 — the switch back and forth as I hover and leave the marker area.
I'm having two problems with this
Nothing happens when I mouseover the marker, but it does happen when I click. On the initial click after the page loads, the map zooms and centers on the building and the marker image resizes. If I click on the building again, nothing else happens, but:
if I click on a menu link that triggers the click event, function buildingFocus(markerName) {google.maps.event.trigger(markerName, "click");} that function resets the icon as if it were the mouseout event.
To test this unexpected behavior further, I commented out each event one at a time. To clarify that something was actually happening, I first changed the initial image to clear.png.
When I took out the mouseover event, the image did not change when I clicked either the building event or the menu link as my first click after the page loaded. Before I removed the mouseover event, clicking on the menu as my second click after page load changed the icon to the mouseout image, but now clicking on the building causes this.
When I took out the mouseout event, clicking on the building as the first click made the icon change to the mouseover image, and clicking again on either area did nothing further. If I clicked on the menu link as the first or future clicks the image didn't change, but it did as soon as I clicked on the building.
When I took the click event out, the image never changed. By itself, the click event works as expected with both locations.
The icon of a marker is not an MVCObject, the API will not observe changes of the icon-properties.
You must modify the url of the icon and then call setIcon to apply the changes:
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
var icon = this.getIcon();
icon.url = 'url/to/icon';
this.setIcon(icon);
});
But I wouldn't suggest it, when you use the icon for multiple markers changing the url(or other properties) will affect the original icon markerIconAcademicCenter (markers use a reference to the original object). You better create a copy with a modified url:
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
var icon = this.getIcon(),copy={};
for(var k in icon){
copy[k]=icon[k];
}
copy.url= 'url/to/icon';
this.setIcon(copy);
});
Try using this :
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
markerIconAcademicCenter.setIcon('url to icon');
});
instead of code below :
google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
markerIconAcademicCenter.url = 'MapIcons/Circle32.png'
});
This will sort out your problem of icon size change on mouseover and mouseout problem.
You can check the code below, so that you will be clear what I mean to say :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places"></script>
<script type="text/javascript">
var map, places, iw;
var markers = [];
var autocomplete;
var options = {
//types: ['(cities)'],
//componentRestrictions: {country: 'us'}
};
var geocoder = new google.maps.Geocoder();
function initialize() {
var myLatlng = new google.maps.LatLng(37.783259, -122.402708);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
places = new google.maps.places.PlacesService(map);
google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
showSelectedPlace();
});
}
function tilesLoaded() {
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', search);
google.maps.event.addListener(map, 'dragend', search);
search();
}
function showSelectedPlace() {
clearResults();
clearMarkers();
var place = autocomplete.getPlace();
map.panTo(place.geometry.location);
markers[0] = new google.maps.Marker({
position: place.geometry.location,
map: map
});
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[0]);
search();
}
function search() {
var type;
for (var i = 0; i < document.controls.type.length; i++) {
if (document.controls.type[i].checked) {
type = document.controls.type[i].value;
}
}
autocomplete.setBounds(map.getBounds());
var search = {
bounds: map.getBounds()
};
if (type != 'establishment') {
search.types = [ type ];
}
places.search(search, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
clearResults();
clearMarkers();
for (var i = 0; i < 9; i++) {
markers[i] = new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(markers[i], 'mouseover', animate(i));
google.maps.event.addListener(markers[i], 'mouseout', reanimate(i));
google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
setTimeout(dropMarker(i), i * 100);
//addResult(results[i], i);
mygetDetails(results[i], i);
}
}
})
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
if (markers[i]) {
markers[i].setMap(null);
markers[i] == null;
}
}
}
function dropMarker(i) {
return function() {
markers[i].setMap(map);
}
}
//Function to animate markers on there hover
function animate(locationCount){
return function(){
markers[locationCount].setIcon('https://mts.googleapis.com/vt/icon/name=icons/spotlight/spotlight-poi.png&scale=2');
$("#addressSpan"+locationCount).css('font-weight', '700');
$("#addressSpan"+locationCount).css('color', '#ff0000');
}
}
//Function to remove animation of markers on there hover
function reanimate(locationCount){
return function(){
markers[locationCount].setIcon('https://mts.googleapis.com/vt/icon/name=icons/spotlight/spotlight-poi.png&scale=1');
$("#addressSpan"+locationCount).css('font-weight', '');
$("#addressSpan"+locationCount).css('color', '');
}
}
function addResult(result, i) {
if(i<=9){
var results = document.getElementById("results");
var tr = document.createElement('tr');
tr.style.backgroundColor = (i% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
tr.click = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var addressTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = result.icon;
icon.setAttribute("class", "placeIcon");
icon.setAttribute("className", "placeIcon");
var name = document.createTextNode(result.name);
var address = document.createTextNode(result.formatted_address);
iconTd.appendChild(icon);
nameTd.appendChild(name);
addressTd.appendChild(address);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
tr.appendChild(addressTd);
results.appendChild(tr);
}
}
function clearResults() {
var results = document.getElementById("results");
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
function clearResults1() {
var results = document.getElementById("results1");
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
function getDetails(result, i) {
return function() {
places.getDetails({
reference: result.reference
}, showInfoWindow(i));
}
}
function mygetDetails(result, i) {
return places.getDetails({
reference: result.reference
}, function(place, status){
if (status == google.maps.places.PlacesServiceStatus.OK) {
addResult(place, i);
}
});
}
function showInfoWindow(i) {
return function(place, status) {
if (iw) {
iw.close();
iw = null;
}
if (status == google.maps.places.PlacesServiceStatus.OK) {
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[i]);
}
}
}
function getIWContent(place) {
var content = "";
content += '<table><tr><td>';
content += '<img class="placeIcon" src="' + place.icon + '"/></td>';
content += '<td><b>' + place.name + '</b>';
content += '</td></tr></table>';
return content;
}
$(function(){
$("#autocomplete").keyup(function(){
clearResults1();
geocoder.geocode({"address": $(this).val()}, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
$.each(data, function(int_index,value) {
var results = document.getElementById("results1");
var tr = document.createElement('tr');
tr.style.backgroundColor = (int_index% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
var nameTd = document.createElement('td');
var name = document.createTextNode(value.formatted_address);
nameTd.appendChild(name);
tr.appendChild(nameTd);
results.appendChild(tr);
});
}
});
});
});
</script>
<style>
body {
font-family: sans-serif;
}
#map_canvas {
position: absolute;
width: 399px;
height: 399px;
top: 25px;
left: 0px;
border: 1px solid grey;
}
#listing {
position: absolute;
width: 200px;
height: 360px;
overflow: auto;
left: 401px;
top: 65px;
cursor: pointer;
}
#listing1 {
position: absolute;
width: 200px;
height: 360px;
overflow: auto;
left: 601px;
top: 65px;
cursor: pointer;
}
#controls {
width: 200px;
position: absolute;
top: 0px;
left: 400px;
height: 60px;
padding: 5px;
font-size: 12px;
}
.placeIcon {
width: 16px;
height: 16px;
margin: 2px;
}
#resultsTable, #resultsTable1{
font-size: 10px;
border-collapse: collapse;
}
#locationField {
width: 400px;
height: 25px;
top: 0px;
left: 0px;
position: absolute;
}
#autocomplete {
width: 400px;
}
</style>
</head>
<body style="margin:0px; padding:0px;" onLoad="initialize()">
<div id="locationField">
<input id="autocomplete" type="text" />
</div>
<div id="controls">
<form name="controls">
<input type="radio" name="type" value="establishment" onClick="search()" checked="checked"/>All<br/>
<input type="radio" name="type" value="restaurant" onClick="search()" />Restaurants<br/>
<input type="radio" name="type" value="lodging" onClick="search()" />Lodging
</form>
</div>
<div id="map_canvas"></div>
<div id="listing"><table id="resultsTable"><tr><td><h3>Suggested<br>Locations</h3></td></tr><tbody id="results"></tbody></table></div>
<div id="listing1"><table id="resultsTable1"><tr><td><h3>Suggested<br>Address</h3></td></tr><tbody id="results1"></tbody></table></div>
</body>
</html>
This is a working example.

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>

Categories

Resources