How to line up an Amcharts single country on google maps api? - google-maps

I am trying to replicate the amcharts demo seen here:
https://www.amcharts.com/docs/v4/tutorials/using-mapchart-with-google-maps-api/
to only show Canada:
What is the best way to lock these two layers together like the amcharts world demo?
I have tried setting bounds, but the zoom scales don't line up. I'm sure there's an easier way that I'm simply not aware of.
var gmap;
function initGoogleMap() {
gmap = new google.maps.Map(document.getElementById("gmap"), {
scrollwheel: true,
center: new google.maps.LatLng(56.130366, -106.346771),
zoom: 3,
disableDefaultUI: true
});
var swBound = new google.maps.LatLng(41.6765556, -141.00275);
var neBound = new google.maps.LatLng(83.3362128, -52.3231981);
var bounds = new google.maps.LatLngBounds(swBound, neBound);
// google.maps.event.addListener(gmap, 'bounds_changed', updateMapPosition);
gmap.fitBounds(bounds);
}
var ammap = am4core.create("ammap", am4maps.MapChart);
ammap.geodata = am4geodata_canadaLow;
ammap.projection = new am4maps.projections.Mercator();
ammap.zoomDuration = 0;
ammap.homeZoomLevel = 0;
ammap.homeGeoPoint = {
latitude: 56.130366,
longitude: -106.346771
};
var polygonSeries = ammap.series.push(new am4maps.MapPolygonSeries());
polygonSeries.useGeodata = true;
ammap.zoomControl = new am4maps.ZoomControl();
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{name}";
polygonTemplate.fill = am4core.color("#74B266");
polygonTemplate.fillOpacity = 0.5;
var hs = polygonTemplate.states.create("hover");
hs.properties.fill = am4core.color("#367B25");
ammap.events.on("zoomlevelchanged", updateMapPosition);
ammap.events.on("mappositionchanged", updateMapPosition);
ammap.events.on("scaleratiochanged", updateMapPosition);
function updateMapPosition(ev) {
if ( typeof gmap === "undefined" )
return;
gmap.setZoom(Math.log2(ammap.zoomLevel) + 3);
gmap.setCenter( {
// a small adjustment needed for this div size:
lat: ammap.zoomGeoPoint.latitude,
lng: ammap.zoomGeoPoint.longitude
} );
}
#maps {
width: 1000px;
height: 500px;
border: 0px solid #eee;
margin: 0px auto;
position: relative;
}
.mapdiv {
width: 1000px;
height: 500px;
position: absolute;
top: 0;
left: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initGoogleMap" defer></script>
<script src="https://www.amcharts.com/lib/4/core.js?ver=5.9.2"></script>
<script src="https://www.amcharts.com/lib/4/maps.js?ver=5.9.2"></script>
<script type='text/javascript' src='https://cdn.amcharts.com/lib/4/geodata/canadaLow.js?ver=5.9.2' id='am-canada-js'></script>
<!-- HTML -->
<div id="maps">
<div id="gmap" class="mapdiv" style="visibility: visible;"></div>
<div id="ammap" class="mapdiv" style="visibility: visible;"></div>
</div>

Related

How add circle Shape in Google maps custom icon?

I have problem with custom images on map.
For example:
My icons generated this way, and icon contains image:
var ic = { //icon
url: icon, // url
scaledSize: new google.maps.Size(30, 30), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0), // anchor
//define the shape
//define the shape
shape:{coords:[17,17,18],type:'circle'},
//set optimized to false otherwise the marker will be rendered via canvas
//and is not accessible via CSS
optimized:false,
title: 'spot'
};
var marker = new google.maps.Marker({
map: map, title: name , position: latlngset, icon: ic
});
I want make my icons like css 50% radius (circle shape).
How I can do it?
Related question: JS Maps v3: custom marker with user profile picture
Using code from there, and changing the border-radius to 50%, gives me a circular icon with the image in the circle.
proof of concept fiddle
//adapted from http://gmaps-samples-v3.googlecode.com/svn/trunk/overlayview/custommarker.html
function CustomMarker(latlng, map, imageSrc) {
this.latlng_ = latlng;
this.imageSrc = imageSrc;
// Once the LatLng and text are set, add the overlay to the map. This will
// trigger a call to panes_changed which should in turn call draw.
this.setMap(map);
}
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.draw = function() {
// Check if the div has been created.
var div = this.div_;
if (!div) {
// Create a overlay text DIV
div = this.div_ = document.createElement('div');
// Create the DIV representing our CustomMarker
div.className = "customMarker"
var img = document.createElement("img");
img.src = this.imageSrc;
div.appendChild(img);
var me = this;
google.maps.event.addDomListener(div, "click", function(event) {
google.maps.event.trigger(me, "click");
});
// Then add the overlay to the DOM
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
// Position the overlay
var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
if (point) {
div.style.left = point.x + 'px';
div.style.top = point.y + 'px';
}
};
CustomMarker.prototype.remove = function() {
// Check if the overlay was on the map and needs to be removed.
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
CustomMarker.prototype.getPosition = function() {
return this.latlng_;
};
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 17,
center: new google.maps.LatLng(37.77088429547992, -122.4135623872337),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var data = [{
profileImage: "http://www.gravatar.com/avatar/d735414fa8687e8874783702f6c96fa6?s=90&d=identicon&r=PG",
pos: [37.77085, -122.41356],
}, {
profileImage: "http://placekitten.com/90/90",
pos: [37.77220, -122.41555],
}]
for (var i = 0; i < data.length; i++) {
new CustomMarker(new google.maps.LatLng(data[i].pos[0], data[i].pos[1]), map, data[i].profileImage)
}
.customMarker {
position: absolute;
cursor: pointer;
background: #424242;
width: 100px;
height: 100px;
/* -width/2 */
margin-left: -50px;
/* -height + arrow */
margin-top: -110px;
border-radius: 50%;
padding: 0px;
}
.customMarker:after {
content: "";
position: absolute;
bottom: -10px;
left: 40px;
border-width: 10px 10px 0;
border-style: solid;
border-color: #424242 transparent;
display: block;
width: 0;
}
.customMarker img {
width: 90px;
height: 90px;
margin: 5px;
border-radius: 50%;
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map" style="width: 640pxpx; height: 480px;">map div</div>
After some google, I found this simple and easiest way for making a marker circle shape. Anyone can also customize it easily.
Here is a sample code -
<script>
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: { lat: 23.8178689, lng: 90.4213642 },
});
const your_img_url = "https://avatars.githubusercontent.com/u/22879378?v=4";
var icon = {
url: your_img_url + '#custom_marker', // url + image selector for css
scaledSize: new google.maps.Size(32, 32), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
const marker = new google.maps.Marker({
position: { lat: 23.8178689, lng: 90.4213642 },
map,
icon: icon,
});
}
</script>
And your CSS style are -
<style>
img[src$="#custom_marker"]{
border: 2px solid #900 !important;
border-radius:50%;
}
</style>
Output:
If you want to make a circular marker just check the documentation This is faster and more lightweight.
Otherwise, just make your actual icon into a circular shape.

How do I stop the Google Maps API from automatically refreshing?

Current behaviour: The page constantly refreshes my location and the entire map.
Desired behaviour: I only want to find and display the current location once, not continuously.
How can I achieve this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>whereami</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript" src="cordova.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key= xyz " type="text/javascript"></script>
<script type="text/javascript">
function onSuccess(position) {
var lat=position.coords.latitude;
var lang=position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat,lang);
var mapOptions = {zoom: 17,center: myLatlng}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({position: myLatlng,map: map});
}
function onError(error) {}
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 0 });
google.maps.event.addDomListener(window, 'load', onSuccess);
</script>
</head>
<body>
<div id="geolocation"></div>
<div id="map-canvas"></div>
</body>
</html>
Don't keep recreating the map. Create the map once (in an "initMap" function), center the map an place the marker in the watchPosition callback function.
jsfiddle
// global variables
var map, marker, polyline;
function initMap() {
// initialize the global map variable
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {
lat: 0,
lng: 0
},
zoom: 1
});
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, {
timeout: 5000
});
}
google.maps.event.addDomListener(window, 'load', initMap);
function onSuccess(position) {
var lat = position.coords.latitude;
var lang = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, lang);
map.setCenter(myLatlng);
map.setZoom(18);
if (marker && marker.setPosition)
marker.setMap(myLatlng); // move the marker
else // create a marker
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
}
function onError(error) {
console.log('ERROR(' + error.code + '): ' + error.message);
}
html {
height: 100%;
width: 100%;
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0
}
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="geolocation"></div>
<div id="map-canvas"></div>

Google map api - autocomplete for hotels

I try to make input field with google map api aucomplete but to search only for hotels...
I try:
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function () {
var places = new google.maps.places.Autocomplete(
(
document.getElementById('hotel')), {
types: ['hotel']
});
// var places = new google.maps.places.Autocomplete(document.getElementById('hotel'));
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
var address = place.formatted_address;
var phone = place.formatted_phone_number;
var name = place.name;
var url = place.website;
$('#address').val(address);
$('#phone').val(phone);
$('#url').val(url);
$('#hotel').val(name);
});
});
</script>
but dont work... What can be a solution here?
This is from https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-hotelsearch
// This example uses the autocomplete feature of the Google Places API.
// It allows the user to find all hotels in a given place, within a given
// country. It then displays markers for all the hotels returned,
// with on-click details for each hotel.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map, places, infoWindow;
var markers = [];
var autocomplete;
var countryRestrict = {'country': 'us'};
var MARKER_PATH = 'https://developers.google.com/maps/documentation/javascript/images/marker_green';
var hostnameRegexp = new RegExp('^https?://.+?/');
var countries = {
'au': {
center: {lat: -25.3, lng: 133.8},
zoom: 4
},
'br': {
center: {lat: -14.2, lng: -51.9},
zoom: 3
},
'ca': {
center: {lat: 62, lng: -110.0},
zoom: 3
},
'fr': {
center: {lat: 46.2, lng: 2.2},
zoom: 5
},
'de': {
center: {lat: 51.2, lng: 10.4},
zoom: 5
},
'mx': {
center: {lat: 23.6, lng: -102.5},
zoom: 4
},
'nz': {
center: {lat: -40.9, lng: 174.9},
zoom: 5
},
'it': {
center: {lat: 41.9, lng: 12.6},
zoom: 5
},
'za': {
center: {lat: -30.6, lng: 22.9},
zoom: 5
},
'es': {
center: {lat: 40.5, lng: -3.7},
zoom: 5
},
'pt': {
center: {lat: 39.4, lng: -8.2},
zoom: 6
},
'us': {
center: {lat: 37.1, lng: -95.7},
zoom: 3
},
'uk': {
center: {lat: 54.8, lng: -4.6},
zoom: 5
}
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: countries['us'].zoom,
center: countries['us'].center,
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false
});
infoWindow = new google.maps.InfoWindow({
content: document.getElementById('info-content')
});
// Create the autocomplete object and associate it with the UI input control.
// Restrict the search to the default country, and to place type "cities".
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */ (
document.getElementById('autocomplete')), {
types: ['(cities)'],
componentRestrictions: countryRestrict
});
places = new google.maps.places.PlacesService(map);
autocomplete.addListener('place_changed', onPlaceChanged);
// Add a DOM event listener to react when the user selects a country.
document.getElementById('country').addEventListener(
'change', setAutocompleteCountry);
}
// When the user selects a city, get the place details for the city and
// zoom the map in on the city.
function onPlaceChanged() {
var place = autocomplete.getPlace();
if (place.geometry) {
map.panTo(place.geometry.location);
map.setZoom(15);
search();
} else {
document.getElementById('autocomplete').placeholder = 'Enter a city';
}
}
// Search for hotels in the selected city, within the viewport of the map.
function search() {
var search = {
bounds: map.getBounds(),
types: ['lodging']
};
places.nearbySearch(search, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
clearResults();
clearMarkers();
// Create a marker for each hotel found, and
// assign a letter of the alphabetic to each marker icon.
for (var i = 0; i < results.length; i++) {
var markerLetter = String.fromCharCode('A'.charCodeAt(0) + (i % 26));
var markerIcon = MARKER_PATH + markerLetter + '.png';
// Use marker animation to drop the icons incrementally on the map.
markers[i] = new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP,
icon: markerIcon
});
// If the user clicks a hotel marker, show the details of that hotel
// in an info window.
markers[i].placeResult = results[i];
google.maps.event.addListener(markers[i], 'click', showInfoWindow);
setTimeout(dropMarker(i), i * 100);
addResult(results[i], i);
}
}
});
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
if (markers[i]) {
markers[i].setMap(null);
}
}
markers = [];
}
// Set the country restriction based on user input.
// Also center and zoom the map on the given country.
function setAutocompleteCountry() {
var country = document.getElementById('country').value;
if (country == 'all') {
autocomplete.setComponentRestrictions({'country': []});
map.setCenter({lat: 15, lng: 0});
map.setZoom(2);
} else {
autocomplete.setComponentRestrictions({'country': country});
map.setCenter(countries[country].center);
map.setZoom(countries[country].zoom);
}
clearResults();
clearMarkers();
}
function dropMarker(i) {
return function() {
markers[i].setMap(map);
};
}
function addResult(result, i) {
var results = document.getElementById('results');
var markerLetter = String.fromCharCode('A'.charCodeAt(0) + (i % 26));
var markerIcon = MARKER_PATH + markerLetter + '.png';
var tr = document.createElement('tr');
tr.style.backgroundColor = (i % 2 === 0 ? '#F0F0F0' : '#FFFFFF');
tr.onclick = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = markerIcon;
icon.setAttribute('class', 'placeIcon');
icon.setAttribute('className', 'placeIcon');
var name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results.appendChild(tr);
}
function clearResults() {
var results = document.getElementById('results');
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
// Get the place details for a hotel. Show the information in an info window,
// anchored on the marker for the hotel that the user selected.
function showInfoWindow() {
var marker = this;
places.getDetails({placeId: marker.placeResult.place_id},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
}
// Load the place information into the HTML elements used by the info window.
function buildIWContent(place) {
document.getElementById('iw-icon').innerHTML = '<img class="hotelIcon" ' +
'src="' + place.icon + '"/>';
document.getElementById('iw-url').innerHTML = '<b><a href="' + place.url +
'">' + place.name + '</a></b>';
document.getElementById('iw-address').textContent = place.vicinity;
if (place.formatted_phone_number) {
document.getElementById('iw-phone-row').style.display = '';
document.getElementById('iw-phone').textContent =
place.formatted_phone_number;
} else {
document.getElementById('iw-phone-row').style.display = 'none';
}
// Assign a five-star rating to the hotel, using a black star ('✭')
// to indicate the rating the hotel has earned, and a white star ('✩')
// for the rating points not achieved.
if (place.rating) {
var ratingHtml = '';
for (var i = 0; i < 5; i++) {
if (place.rating < (i + 0.5)) {
ratingHtml += '✩';
} else {
ratingHtml += '✭';
}
document.getElementById('iw-rating-row').style.display = '';
document.getElementById('iw-rating').innerHTML = ratingHtml;
}
} else {
document.getElementById('iw-rating-row').style.display = 'none';
}
// The regexp isolates the first part of the URL (domain plus subdomain)
// to give a short URL for displaying in the info window.
if (place.website) {
var fullUrl = place.website;
var website = hostnameRegexp.exec(place.website);
if (website === null) {
website = 'http://' + place.website + '/';
fullUrl = website;
}
document.getElementById('iw-website-row').style.display = '';
document.getElementById('iw-website').textContent = website;
} else {
document.getElementById('iw-website-row').style.display = 'none';
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
table {
font-size: 12px;
}
#map {
width: 440px;
}
#listing {
position: absolute;
width: 200px;
height: 470px;
overflow: auto;
left: 442px;
top: 0px;
cursor: pointer;
overflow-x: hidden;
}
#findhotels {
position: absolute;
text-align: right;
width: 100px;
font-size: 14px;
padding: 4px;
z-index: 5;
background-color: #fff;
}
#locationField {
position: absolute;
width: 190px;
height: 25px;
left: 108px;
top: 0px;
z-index: 5;
background-color: #fff;
}
#controls {
position: absolute;
left: 300px;
width: 140px;
top: 0px;
z-index: 5;
background-color: #fff;
}
#autocomplete {
width: 100%;
}
#country {
width: 100%;
}
.placeIcon {
width: 20px;
height: 34px;
margin: 4px;
}
.hotelIcon {
width: 24px;
height: 24px;
}
#resultsTable {
border-collapse: collapse;
width: 240px;
}
#rating {
font-size: 13px;
font-family: Arial Unicode MS;
}
.iw_table_row {
height: 18px;
}
.iw_attribute_name {
font-weight: bold;
text-align: right;
}
.iw_table_icon {
text-align: right;
}
<div id="findhotels">
Find hotels in:
</div>
<div id="locationField">
<input id="autocomplete" placeholder="Enter a city" type="text" />
</div>
<div id="controls">
<select id="country">
<option value="all">All</option>
<option value="au">Australia</option>
<option value="br">Brazil</option>
<option value="ca">Canada</option>
<option value="fr">France</option>
<option value="de">Germany</option>
<option value="mx">Mexico</option>
<option value="nz">New Zealand</option>
<option value="it">Italy</option>
<option value="za">South Africa</option>
<option value="es">Spain</option>
<option value="pt">Portugal</option>
<option value="us" selected>U.S.A.</option>
<option value="uk">United Kingdom</option>
</select>
</div>
<div id="map"></div>
<div id="listing">
<table id="resultsTable">
<tbody id="results"></tbody>
</table>
</div>
<div style="display: none">
<div id="info-content">
<table>
<tr id="iw-url-row" class="iw_table_row">
<td id="iw-icon" class="iw_table_icon"></td>
<td id="iw-url"></td>
</tr>
<tr id="iw-address-row" class="iw_table_row">
<td class="iw_attribute_name">Address:</td>
<td id="iw-address"></td>
</tr>
<tr id="iw-phone-row" class="iw_table_row">
<td class="iw_attribute_name">Telephone:</td>
<td id="iw-phone"></td>
</tr>
<tr id="iw-rating-row" class="iw_table_row">
<td class="iw_attribute_name">Rating:</td>
<td id="iw-rating"></td>
</tr>
<tr id="iw-website-row" class="iw_table_row">
<td class="iw_attribute_name">Website:</td>
<td id="iw-website"></td>
</tr>
</table>
</div>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap"
async defer></script>
Unfortunately, this isn't possible.
The Place Autocomplete API doesn't support filtering to only hotel results. The list of supported types for Autocomplete filtering is documented on the Google Developers site: Types supported in place autocomplete requests. hotel is not in the list.

Google MAP API, Determine if a route passes by a polygon

I have a map that shows 3 polygons and a route that passes a cross them. Each polygone has a title property. I would like to display a polygone title when the route passes by it.
This is the code I did :
<!doctype html><html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<title>Loading / Editing Zones</title>
<style>
#map, html, body { padding: 0; margin: 0; height: 100%; } #panel { width: 200px; font-family: Arial, sans-serif; font-size: 13px; float: right; margin: 10px; } #delete-button { margin-top: 5px; } #login_close{ display: none; } .labels { color: red; background-color: white; font-family: "Lucida Grande", "Arial", sans-serif; font-size: 10px; font-weight: bold; text-align: center; width: 65px; border: 2px solid black; white-space: nowrap; } .autocomplete-suggestions { border: 1px solid #999; background: #FFF; overflow: auto; } .autocomplete-suggestion { padding: 2px 5px; white-space: nowrap; overflow: hidden; } .autocomplete-selected { background: #F0F0F0; } .autocomplete-suggestions strong { font-weight: normal; color: #3399FF; }
</style>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing,geometry" type="text/javascript"></script>
<script type="text/javascript">
var directionsDisplay = new google.maps.DirectionsRenderer(),
directionsService = new google.maps.DirectionsService(),
polys = new Array(),
map = null,
zoom = 10,
myPolygons =
[
{
"name": "zone1",
"coordinates": [
"51.44459,-0.21835",
"51.46256,-0.11261",
"51.43004,0.03708",
"51.40777,-0.09888",
"51.39064,-0.21149",
"51.40692,-0.27191"
]
},
{
"name": "zone2",
"coordinates": [
"51.56683,-0.22934",
"51.54292,-0.13046",
"51.57195,0",
"51.59755,-0.03708",
"51.5984,-0.13733",
"51.59755,-0.19913"
]
},
{
"name": "zone3",
"coordinates": [
"51.66148,-0.13733",
"51.61461,-0.08514",
"51.61887,0.02197",
"51.65381,0.05905",
"51.64359,-0.04807"
]
}
];
function drawPolygon(poly, polyLabel) {
var options = {
paths: poly,
strokeColor: '#AA2143',
strokeOpacity: 1,
strokeWeight: 2,
fillColor: "#FF6600",
fillOpacity: 0.7,
polyTitle: polyLabel
};
newPoly = new google.maps.Polygon(options);
newPoly.setMap(map);
polys.push(newPoly);
}
function sendPolygonForDrawing() {
for(var i =0; i<myPolygons.length; i++){
poly = new Array();
var coord = myPolygons[i].coordinates;
var lng = coord.length;
for(var j=0; j<lng; j++){
var longit_Latid = coord[j].split(',');
poly.push(new google.maps.LatLng(parseFloat(longit_Latid[0]), parseFloat(longit_Latid[1])));
}
drawPolygon(poly, myPolygons[i].name);
poly.pop();
}
}
//Route
function calcRoute() {
var start = "Croydon";
var end = "Cheshunt";
var waypts = [];
var waysArray = ["London"];
for (var i = 0; i < waysArray.length; i++) {
waypts.push({
location:waysArray[i],
stopover:true});
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var routCoordinates = fncRouteZoneIntersection(response);//this function populates the routCoordinates with the JSON data of the route.
var exist = new Array();
for(var i=0; i<polys.length; i++){//polys holds all polygons objects.
for(var j=0; j<routCoordinates.length; j++){
if(google.maps.geometry.poly.containsLocation(new google.maps.LatLng(routCoordinates[j].k, routCoordinates[j].A), polys[i]) == true){
exist .push(polys.polyTitle);
break;
/*this breaks the loop checking when a point is found inside a polygon
and go check the next one, because knowing that one point of the route is
inside a polygon is enough*/
}
}
}
console.log(exist);
alert(exist);
}
});
directionsDisplay.setMap(map);
}
function fncRouteZoneIntersection(response){
var myRoute = response.routes[0].legs[0];
var lngLatCordinates = new Array();
for (var i = 0; i < myRoute.steps.length; i++) {
lngLatCordinates.push(myRoute.steps[i].start_point);
}
return lngLatCordinates;
}
$(function() {
//Basic
var cartodbMapOptions = {
zoom: zoom,
center: new google.maps.LatLng(51.465872, -0.065918),
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Init the map
map = new google.maps.Map(document.getElementById("map"),cartodbMapOptions);
sendPolygonForDrawing();
calcRoute();
var drawingManager = new google.maps.drawing.DrawingManager({
drawingControl: false,
polygonOptions: {
fillColor: '#0099FF',
fillOpacity: 0.7,
strokeColor: '#AA2143',
strokeWeight: 2,
clickable: true,
zIndex: 1,
editable: true
}
});
});
</script>
<div id="map">
</div>
</body>
</html>
Sounds like my code starting from the line : var routCoordinates = fncRouteZoneIntersection(response);............ is only checking the starting, waypoint and the end of the route against the polygons and not all the route points that is why I get an empty array when doing the check.
Can any one help me please?
You have to use overview_path instead of route legs. See docs overview_path contains an array of LatLngs that represent an approximate (smoothed) path of the resulting directions.
function fncRouteZoneIntersection(response) {
console.log('fncRouteZoneIntersection...');
// var myRoute = response.routes[0].legs[0];
var myRoute = response.routes[0].overview_path;
var lngLatCordinates = new Array();
// for (var i = 0; i < myRoute.steps.length; i++) {
for (var i = 0; i < myRoute.length; i++) {
// lngLatCordinates.push(myRoute.steps[i].start_point);
lngLatCordinates.push(myRoute[i]);
}
// console.log(lngLatCordinates);
return lngLatCordinates;
}
and you have to change:
exist.push(polys.polyTitle);
to
exist.push(polys[i].polyTitle);
See example at jsbin with markers. List of polygon titles is written to console.log.

Info window showing empty / blank on Google Fusion Map layers

I'm trying to make a side by side Google Fusion Map and while that seems to be working OK, when I click on a polygon, the info window shows up as blank.
I'm trying to work out why it might not be picking up and displaying the information from the table, when the rest of the data seems to be showing up.
The map is here: http://clairemiller.net/blaenaupop.html
The code I'm using to display that is:
<!DOCTYPE html>
<html>
<head>
<style>
#map_canvas { width: 335px; height: 400px; float: left}
#map_canvas2 { width: 335px; height: 400px; }
#image {float: bottom}
body { margin: 0px}
p {color: white; font-family: arial; font-size: 12px; margin: 0px; position: relative; left: 4px; top: 3px }
#left { width: 335px; height: 20px; float: left; background-color: #007A8F}
#right { width: 335px; height: 20px; float: left; background-color: #005F70}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
var map;
var layer;
var layer2;
var secondMapMove = false;
var secondMapBounds = false;
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(51.787578, -3.204393),
zoom: 12,
mapTypeId: 'roadmap'
});
var layer = new google.maps.FusionTablesLayer({
center: new google.maps.LatLng(51.5021181, -3.17909),
query: {
select: 'geometry',
from: '1F3SbppvMyF-3lcT5zrYS8S1X8JD1G2-0aQkWLPw',
}
});
layer.setMap(map);
map2 = new google.maps.Map(document.getElementById('map_canvas2'), {
zoom: 12,
mapTypeId: 'roadmap'
});
var layer2 = new google.maps.FusionTablesLayer({
center: new google.maps.LatLng(53.13359,-1.955566),
query: {
select: 'geometry',
from: '1Hf9Z80JTCiq-zWwhhSPrbifO7q9dvA_DP_BN8IY',
}
});
layer2.setMap(map2);
google.maps.event.addListener(map,'zoom_changed',function(){
if(secondMapBounds!=true) {
var tmpZoom = map.getZoom();
map2.setZoom(tmpZoom);
} else {
secondMapBounds = false;
}
});
google.maps.event.addListener(map2,'zoom_changed',function(){
secondMapBounds = true;
var tmpZoom1 = map2.getZoom();
map.setZoom(tmpZoom1);
});
google.maps.event.addListener(map,'bounds_changed',function(){
if(secondMapMove!=true) {
var tmpBounds = map.getCenter();
map2.setCenter(tmpBounds);
} else {
secondMapMove=false;
}
});
google.maps.event.addListener(map2,'bounds_changed',function(){
secondMapMove = true
var tmpBounds2 = map2.getCenter();
map.setCenter(tmpBounds2);
});
}
</script>
</head>
<body onload="initialize();">
<div class="mapMap" id="map_canvas"></div>
<div class="mapMap" id="map_canvas2"></div>
</body>
</html>
The IDs for the two tables are in there, the infowindow appears to be showing up fine on them.
I'm wondering what I've missed that is causing the infowindows to show up blank.
It doesn't show blank, it shows white.
The contents of the infoWindows are inside <p/>-elements, the background of the infoWindows is white, and this is your CSS:
p {color: white;/*......*/}
change the color
.googft-info-window p{color:#000;}