Google Maps API - Location markers hiding - javascript

I am a novice with Google maps API. So far, I have managed to get my markers in layers. But as I select multiple layers to show, some of my markers hide. Even if I zoom all the way, I am unable to view them. When I unchecked one of the other layers, the markers come back. Is there some code that I can add to fix this?
This is what I have so far hosted on Kissr sites: Version 1 - Maps
This is my most recent code on github: Github Code
This is my html file.
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDYLjSN23UIORWpyQ-09Qd6dz7M2KNydQk&sensor=false"></script>
<script type="text/javascript" src="vars.js" ></script>
<script>
function initialize() {
var MaristCollege = {
center : schoolCenter,
zoom : 16,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), MaristCollege);
check();
}
function check() {
if (document.getElementById('lan-rooms').checked) {
lanRooms.setMap(map);
} else {
lanRooms.setMap(null);
}
if (document.getElementById('man-holes').checked) {
manHoles.setMap(map);
} else {
manHoles.setMap(null);
}
if (document.getElementById('conduits-trail').checked){
conduitPathMcD.setMap(map);
conduitPathMrG.setMap(map);
} else {
conduitPathMcD.setMap(null);
conduitPathMrG.setMap(null);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
Layer Selection
<label>
<input type="checkbox" name="checkbox" id="lan-rooms" onclick="check()" value="value">
Lan Rooms </label>
<label>
<input type="checkbox" name="checkbox" id="man-holes" onclick="check()" value="value">
Man Holes </label>
<label>
<input type="checkbox" name="checkbox" id="conduits-trail" onclick="check()" value="value">
Conduit Paths</label>
<div id="googleMap" style="width:100%;height:850px;"></div>
</body>
</html>
This is the code from my JS file that puts in the Fusiontables.
//school coordinate
var schoolCenter = new google.maps.LatLng(41.722937, -73.936533);
var map;
//lan room locations found in a fusion table
var lanRooms = new google.maps.FusionTablesLayer({
query : {
select : 'Location',
from : '1Mn-40rJ6-r7gjFfnVCqy3AS6Xc9flaiowjQTFbk'
},
styles : [{
markerOptions : {
iconName : 'small_green'
}
}]
});
//manhole location created in a fusion table
var manHoles = new google.maps.FusionTablesLayer({
query : {
select : 'Location',
from : '1EOtteMYME1OzNuF2pHT7KZqo1qKLWCWQian0RzM'
},
});

Related

How to layer point feature over a polygon feature

How can I get a point feature over a polygon feature? I am layering polygon on top of the point feature or a marker feature however I also have a tooltip (popup) that fires when hovering over the features but only the polygon popup is getting displayed even when I am hovering over the point/marker feature. I am assured the point/marker is over/on top of the polygon because I assigned a 1.0 opacity and point/marker is still visible.
So when a point is on top of a polygon how can I get the popup on the point/marker feature to fire? Or is this a potential defect?
I swapped out the hover event for a 'click' event on the point/marker feature and the popup works as expected but this is not the desired behavior.
TIA!
Rick...
I've done a bunch of experimenting and its the order in which the events are added that make all the difference, not the order of the layers in this case. Unless you add the events to the map, rather than the individual layers, then the rendering order is used.
I've put together a little test app to test all the different scenarios:
var map, datasource, output, polygonLayer, pointLayer, isSwapped = false;
function GetMap() {
output = document.getElementById('output');
//Initialize a map instance.
map = new atlas.Map('myMap', {
center: [-122.1255, 47.6305],
zoom: 17,
view: 'Auto',
//Add your Azure Maps subscription key to the map SDK. Get an Azure Maps key at https://azure.com/maps
authOptions: {
authType: 'subscriptionKey',
subscriptionKey: subscriptionKey
}
});
//Wait until the map resources are ready.
map.events.add('ready', function() {
//Create a data source and add it to the map.
datasource = new atlas.source.DataSource();
map.sources.add(datasource);
//Add polygon to data source.
datasource.add(new atlas.data.Polygon(
[
[
[-122.126, 47.63096],
[-122.12602, 47.62997],
[-122.12537, 47.62994],
[-122.12534, 47.63094],
[-122.12600, 47.63096]
]
]
));
//Add point data
datasource.add(new atlas.data.Point([-122.1255, 47.6305]));
polygonLayer = new atlas.layer.PolygonLayer(datasource, null, {
fillColor: 'red'
});
pointLayer = new atlas.layer.SymbolLayer(datasource, null, {
filter: ['==', ['geometry-type'], 'Point']
});
map.layers.add([polygonLayer, pointLayer]);
map.events.add('mousemove', layerHovered);
});
}
function layerHovered(e) {
var msg = [];
if (e.shapes && e.shapes.length > 0) {
msg.push(e.shapes.length, ' shapes hovered.<ul>');
e.shapes.forEach(s => {
if (s instanceof atlas.Shape) {
msg.push('<li>Shape: ', s.getType(), '</li>');
} else {
msg.push('<li>Feature: ', s.geometry.type, ' (', s.source, ' -> ', s.sourceLayer, ')</li>');
}
});
msg.push('</ul>');
}
output.innerHTML = msg.join('');
}
function swapLayerOrder() {
map.layers.remove([pointLayer, polygonLayer]);
if (isSwapped) {
map.layers.add([polygonLayer, pointLayer]);
} else {
map.layers.add([pointLayer, polygonLayer]);
}
isSwapped = !isSwapped;
}
function changeEvents(elm) {
map.events.remove('mousemove', layerHovered);
map.events.remove('mousemove', pointLayer, layerHovered);
map.events.remove('mousemove', polygonLayer, layerHovered);
switch (elm.value) {
case 'map':
map.events.add('mousemove', layerHovered);
break;
case 'ps':
map.events.add('mousemove', [polygonLayer, pointLayer], layerHovered);
break;
case 'sp':
map.events.add('mousemove', [pointLayer, polygonLayer], layerHovered);
break;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8" />
<!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
<link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" type="text/css" />
<script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
</head>
<body onload="GetMap()">
<div id="myMap" style="position:relative;width:100%;height:600px;"></div>
<div style="position:absolute;top: 10px;left:10px;background-color:white;padding:10px;">
<input type="button" onclick="swapLayerOrder()" value="Swap layer order"/>
<br/><br/>
Attach event to:<br/>
<input type="radio" name="gender" value="map" checked="checked" onclick="changeEvents(this)"/> map<br/>
<input type="radio" name="gender" value="ps" onclick="changeEvents(this)"/> polygon layer then symbol layer<br/>
<input type="radio" name="gender" value="sp" onclick="changeEvents(this)"/> symbol layer then polygon layer<br/>
<br/>
<div id="output"></div>
</div>
<script>var subscriptionKey = atob('dFRrMUpWRWFlTnZEa3h4bnhIbTljWWFDdnFsT3ExdS1mWFR2eVhuMlhrQQ==')</script>
</body>
</html>

Adding searchable map to Wordpress

I am a novice at fusion tables and google maps APIs, so hopefully the answer is straight forward! I have used fusion tables to create a map of data points and added a search function.
However, the map only appears briefly before disappearing to be replaced by a "Sorry, something went wrong message". I have reviewed the code and can't work out where the error is.
Please could someone take a look and advise what needs to change?.
Here is the link to the page: https://www.enablie.co.uk/map-test/
My code is:
<!DOCTYPE html>
<html>
<head>
<style>
#map-canvas { width:800px; height:800px; }
.layer-wizard-search-label { font-family: sans-serif };
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layer_0;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(52.90081096506728, -0.8806991343750425),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer_0 = new google.maps.FusionTablesLayer({
query: {
select: "col2",
from: "1LP8RhZ3QlYREIJB3e1xogaHWVmL8qxAUjKW1R6XE"
},
map: map,
styleId: 2,
templateId: 2
});
}
function changeMap_0() {
var whereClause;
var searchString = document.getElementById('search-string_0').value.replace(/'/g, "\\'");
if (searchString != '--Select--') {
whereClause = "'School Name' CONTAINS IGNORING CASE '" + searchString + "'";
}
layer_0.setOptions({
query: {
select: "col2",
from: "1LP8RhZ3QlYREIJB3e1xogaHWVmL8qxAUjKW1R6XE",
where: whereClause
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div style="margin-top: 10px;">
<label class="layer-wizard-search-label">
School Name
<input type="text" id="search-string_0">
<input type="button" onclick="changeMap_0()" value="Search">
</label>
</div>
</body>
</html>
Where is your map init with AppId & AppSecret keys ? You must call Google App using this on init of your page (see this Google Map Api JS)
https://developers.google.com/maps/documentation/javascript/examples/map-simple

JavaScript, Google Maps API and Wordpress

I am trying to set up a price calculation tool in JS. This is going to calculate amount of kilometers between a set address (business address) and the customer's address, which they can enter into an <input> field.
The script will then round off the amount of kilometers to whole euros (no decimals), and display this as the price (charge of this service is 1 euro per kilometer, so no other calculation required to get the price).
So far I came up with the below code. When I enter this into a .html document in notepad, and open that file with Firefox, it works. However, this needs to be implemented on a Wordpress website.
I put the JS code in the <head> and the rest in the <body> (as shown below). But for some reason it won't work in Wordpress. (on the Wordpress site, as well as the notepad file, I put the script between <script> tags of course)
I tried reading the Wordpress documentation about using JS, and as far as I can see, pasting the code directly into the header is a valid way of making it work (especially for testing purposes) and everything should work, but evidently doesn't. I have also used Google, as well as the Stackoverflow search to try and find an answer, but was obviously unsuccessful.
All help would be greatly appreciated!
The website on which it should be, but isn't, working is: http://www.aircostadskanaal.nl/haal-en-breng-service/
The <head>:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var melbourne = new google.maps.LatLng(-37.813187, 144.96298);
var myOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: melbourne
}
}
function calcRoute() {
var start = "Ceresstraat 11, Stadskanaal, Netherlands";
var end = document.getElementById("end").value;
var distanceInput = document.getElementById("distance");
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
distanceInput.value = Math.round(response.routes[0].legs[0].distance.value / 1000);
}
});
}
The <body>:
<body onload="initialize()">
<div>
<p>
<!--<label for="start">Start: </label>
//<input type="text" name="start" id="start" />-->
<label for="end">Adres: </label>
<input type="text" name="end" id="end" />
<input type="submit" value="OK" onclick="calcRoute()" />
</p>
<p>
<label for="distance">Prijs (€): </label>
<input type="text" name="distance" id="distance" readonly="true" />
</p>
</div>
edit; removed line to set map as I decided not to include the map on the website. This has not fixed the problem unfortunately.
The line map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); in function initialize is referencing element with id="map_canvas" but I can't see it in the markup. Did you by any chance forget it?
Found the answer myself. Thanks everyone for your input
The issue was directionsDisplay = new google.maps.DirectionsRenderer(); which was defined as a variable in function initialize(), but also used in function calcRoute().
I defined it as a global variable, and now the script works.

Why wont Google Maps API Key recognise my referrer URL?

I have a html file on my website domain (devodeliver.co.uk) which calls on my API Key with the code.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY-KEY"></script>
In the Developers Console I have tried adding every combination of my domain URL as you can see below
But when I load my site it shows the map for a millisecond then returns with the error "Google Maps API error: InvalidKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error_.bb # MY-KEY:32" - basically saying I haven't given my website permission to access that API Key. But even if I don't set any referrers, it come back with the same error message. I've also waited way over 5 minutes for the API to take affect. Please, what am I doing wrong?! I've spent almost 16 hours trying to figure this out & I can't seem to for the life of me. HELPPPP!
Full HTML code:
<html>
<head>
<style type="text/css">
#map
{
height:400px;
width:400px;
display:block;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7-LTLEupUWBJBWl1GpOWPwkMvxzf8itQ"></script>
<script type="text/javascript">
function getPosition(callback) {
var geocoder = new google.maps.Geocoder();
var postcode = document.getElementById("postcode").value;
geocoder.geocode({'address': postcode}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
callback({
latt: results[0].geometry.location.lat(),
long: results[0].geometry.location.lng()
});
}
});
}
function setup_map(latitude, longitude) {
var _position = { lat: latitude, lng: longitude};
var mapOptions = {
zoom: 16,
center: _position
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marker = new google.maps.Marker({
position: mapOptions.center,
map: map
});
}
window.onload = function() {
setup_map(51.5073509, -0.12775829999998223);
document.getElementById("form").onsubmit = function() {
getPosition(function(position){
var text = document.getElementById("text")
text.innerHTML = "Marker position: { Longitude: "+position.long+ ", Latitude:"+position.latt+" }";
setup_map(position.latt, position.long);
});
}
}
</script>
</head>
<body>
<form action="javascript:void(0)" id="form">
<input type="text" id="postcode" placeholder="Enter a postcode">
<input type="submit" value="Show me"/>
</form>
<div id="map"></div>
<div id="text"></div>
</body>
</html>
Here, when I tested it, it gives me the error "Google Maps API error: ApiNotActivatedMapError" on the JS console.
Take a look for this issue on: https://developers.google.com/maps/documentation/javascript/error-messages#deverrorcodes
When you use a library or service via the Maps-Javascript-API, and use a key, you need to activate the Google Maps JavaScript API .
Make sure to activate the Google Maps JavaScript API for your project.
Also,
take a look on this other topic about Enable the Google Maps Jvascript API: Google Map error: InvalidKeyOrUnauthorizedURLMapError

Putting Javascript into Google Sites

I am having problems embedding my query from google fusion into google sites. I have created the query and it works as a html file that has been saves in notepad, but when I go to put it in my Google Sites website it does not work.
The Query code is:
<html>
<head>
<style>
#map-canvas { width:850px; height:650px; }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layerl0;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(43.89591323557617, -79.77653503417969),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layerl0 = new google.maps.FusionTablesLayer({
query: {
select: "'col2'",
from: '1eMaZWdi5QhF1252KH2e7xOiNyJoBFOzpStMP-Ks'
},
map: map,
styleId: -1,
templateId: -1
});
}
function changeMapl0() {
var searchString = document.getElementById('search-string-l0').value.replace(/'/g, "\\'");
layerl0.setOptions({
query: {
select: "'col2'",
from: '1eMaZWdi5QhF1252KH2e7xOiNyJoBFOzpStMP-Ks',
where: "'description' CONTAINS IGNORING CASE '" + searchString + "'"
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div style="margin-top: 10px;">
<label>Land use:</label><input type="text" id="search-string-l0">
<input type="button" onclick="changeMapl0()" value="Search">
</div>
</body>
Have you tried using Google Gadgets to get your code to work in Sites? That is, put the code into a Google Gadget, and then adding the Gadget to your Sites Page via the Insert Menu in the Editor).
Start here, if you have not already:
https://developers.google.com/gadgets/
Another option is to use the HTML box, or making an Apps Script.

Categories

Resources