I've looked through a lot of the similar questions on here, but have not found anything that will answer my question. I am new to JS and GoogleMaps API v3, and have successfully followed their tutorials to get this far. However, I'd like to have an infowindow with custom content appear based on which marker is clicked, and I cannot figure out how to do this. I'd also like to have this be possible with around 100 markers, so I'd like to know the best way to do this as well without things getting too messy. To be clear, there are 3 types of icons, but there will eventually be many markers associated with each icon, so I will need content linked to each "feature". Hopefully I've got a good start here and am not way off base. I've included the code for the page. Thank you so much in advance for any help anyone can provide.
<!DOCTYPE html>
<html>
<head>
<style>
#map_canvas {
width: 800px;
height: 500px;
background-color:#CCC;
}
#legend {
font-family: Arial, sans-serif;
background: #fff;
padding: 10px;
margin: 10px;
border: 3px solid #000;
}
#legend img {
vertical-align: middle;
}
</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(33.137551,-0.703125),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(map_canvas, map_options);
map.set('styles', [
{
featureType: 'road',
elementType: 'geometry',
stylers: [
{ color: '#888888' },
{ weight: 1.0 }
]
}, {
featureType: 'landscape',
elementType: 'geometry.fill',
stylers: [
{ hue: '#008f11' },
{ gamma: 1.0 },
{ saturation: 0 },
{ lightness: -10 }
]
}, {
featureType: 'water',
elementType: 'geometry.fill',
stylers: [
{ hue: '#054d8fd' },
{ gamma: 1.0 },
{ saturation: 0 },
{ lightness: -10 }
]
}, {
featureType: 'poi',
elementType: 'geometry',
stylers: [
{ visibility: 'off' }
]
}
]);
var iconBase = 'http://i1318.photobucket.com/albums/t658/greatergoodorg/';
var icons = {
people: {
name: 'People',
icon: iconBase + 'people_zps26d13009.png',
shadow: iconBase + 'shadow-people_zps4b39eced.png'
},
pets: {
name: 'Pets',
icon: iconBase + 'pets_zps15f549f2.png',
shadow: iconBase + 'shadow-pets_zps361068aa.png'
},
planet: {
name: 'Planet',
icon: iconBase + 'planet_zps2a8572ce.png',
shadow: iconBase + 'shadow-planet_zps9912e26b.png',
}
};
var data = ["This is the first one", "This is the second one", "This is the third one"];
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
shadow: {
url: icons[feature.type].shadow,
anchor: new google.maps.Point(21, 32)
},
animation: google.maps.Animation.DROP,
map: map
});
/*...
google.maps.event.addListener(marker, "click", function () {
infowindow.open(map,marker);
});
...*/
/*...
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
});
...*/
}
var features = [
{
position: new google.maps.LatLng(33.137551,-0.703125),
type: 'planet'
},
{
position: new google.maps.LatLng(44.234234,-0.232233),
type: 'pets'
},
{
position: new google.maps.LatLng(54.234234,-0.032233),
type: 'people'
}
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
var legend = document.getElementById('legend');
for (var key in icons) {
var type = icons[key];
var name = type.name;
var icon = type.icon;
var div = document.createElement('div');
div.innerHTML = '<img src="' + icon + '"> ' + name;
legend.appendChild(div);
}
map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(
document.getElementById('legend'));
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
<div id="legend"><strong>Project Types</strong></div>
</body>
</html>
This will open an infowindow and display the "type" string in it
var infowindow = new google.maps.InfoWindow();
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
shadow: {
url: icons[feature.type].shadow,
anchor: new google.maps.Point(21, 32)
},
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(feature.type);
infowindow.open(map,marker);
});
}
Related
I have Google Maps:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Fusion Tables layers</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
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: 39.8282, lng: -98.5795}
});
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoom_level = map.getZoom();
var layer;
var layer1;
//state level
if(zoom_level >= 5 && zoom_level < 7) {
layer = new google.maps.FusionTablesLayer({
query: {
select: '\'geometry\'',
from: '17aT9Ud-YnGiXdXEJUyycH2ocUqreOeKGbzCkUw'
},
styles: [{
polygonOptions: {
fillColor: '#000000',
fillOpacity: 0.001
}
}]
});
layer.setMap(map);
}
//county level
if(zoom_level >= 7) {
layer = null;
layer.setMap(null);
layer1 = new google.maps.FusionTablesLayer({
query: {
select: '\'geometry\'',
from: '1xdysxZ94uUFIit9eXmnw1fYc6VcQiXhceFd_CVKa'
},
styles: [{
polygonOptions: {
fillColor: '#000000',
fillOpacity: 0.001
}
}]
});
layer1.setMap(map);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBMtoh9P3UkoxbXndKu_HOP7KsVwTRvxGU&callback=initMap">
</script>
</body>
</html>
When I zoom in to zoomlevel 7 and above, I still see state level (layer) and not layer1. How can I reset layer when zoom in?
I would suggest that if you only ever want one layer at a time, only create one, hide it before creating a new version.
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoom_level = map.getZoom();
if (layer) layer.setMap(null);
//state level
if (zoom_level >= 5 && zoom_level < 7) {
layer = new google.maps.FusionTablesLayer({
query: {
select: '\'geometry\'',
from: '17aT9Ud-YnGiXdXEJUyycH2ocUqreOeKGbzCkUw'
},
styles: [{
polygonOptions: {
fillColor: '#000000',
fillOpacity: 0.001
}
}]
});
layer.setMap(map);
}
//county level
if (zoom_level >= 7) {
layer = new google.maps.FusionTablesLayer({
query: {
select: '\'geometry\'',
from: '1xdysxZ94uUFIit9eXmnw1fYc6VcQiXhceFd_CVKa'
},
styles: [{
polygonOptions: {
fillColor: '#000000',
fillOpacity: 0.001
}
}]
});
layer.setMap(map);
}
});
proof of concept fiddle
code snippet:
var layer;
var layer1;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: 39.8282,
lng: -98.5795
}
});
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoom_level = map.getZoom();
if (layer) layer.setMap(null);
//state level
if (zoom_level >= 5 && zoom_level < 7) {
layer = new google.maps.FusionTablesLayer({
query: {
select: '\'geometry\'',
from: '17aT9Ud-YnGiXdXEJUyycH2ocUqreOeKGbzCkUw'
},
styles: [{
polygonOptions: {
fillColor: '#000000',
fillOpacity: 0.001
}
}]
});
layer.setMap(map);
}
//county level
if (zoom_level >= 7) {
layer = new google.maps.FusionTablesLayer({
query: {
select: '\'geometry\'',
from: '1xdysxZ94uUFIit9eXmnw1fYc6VcQiXhceFd_CVKa'
},
styles: [{
polygonOptions: {
fillColor: '#000000',
fillOpacity: 0.001
}
}]
});
layer.setMap(map);
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
What is the correct way to specify the stroke color inline, for each Feature object in the constructor of a FeatureCollection GeoJSON object? I am trying many ways to set it blue below, but the result is still the default black stroke color. Thanks!
Fiddle
<head>
<title>LineString Colors</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 33.9720, lng: -81.0527},
zoom: 6
});
map.data.addGeoJson({
"type": "FeatureCollection",
"features": [
{"type": "Feature",
"geometry":
{"type": "LineString",
"coordinates": [[-81.0527, 33.9720],
[-79.6651, 34.9167],
[-85.0252, 38.6221]],
"strokeColor": "#0000FF",
},
"strokeColor": "#0000FF",
"style": {"strokeColor": "#0000FF"}
}
],
"strokeColor": "#0000FF"
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
</body>
See the documentation on Styling GeoJson data
If you just want all the polylines to be blue, all you have to do is:
map.data.setStyle(function (feature) {
return {
strokeColor: "#0000FF"
};
});
But, if as you imply in your title, you want to specify the colors in the GeoJSON, you can set strokeColor in the properties of the feature, then you can retrieve it with getProperty:
var strokeColor = feature.getProperty('strokeColor');
Then use that to set the color of the polyline dynamically:
map.data.setStyle(function (feature) {
var strokeColor = feature.getProperty('strokeColor');
return {
strokeColor: strokeColor,
strokeWeight: 2
};
});
proof of concept fiddle
code snippet:
var map;
function initMap() {
var gbounds = new google.maps.LatLngBounds();
gbounds.extend(new google.maps.LatLng(33.9720039368, -81.052734375));
gbounds.extend(new google.maps.LatLng(34.9167518616, -79.6651229858));
map = new google.maps.Map(document.getElementById('map'), {
center: gbounds.getCenter(),
zoom: 6
});
map.data.setStyle(function(feature) {
var strokeColor = feature.getProperty('strokeColor');
return {
strokeColor: strokeColor,
strokeWeight: 2
};
});
map.data.addGeoJson({
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-81.052734375, 33.9720039368],
[-79.665122985799997, 34.916751861599998],
[-85.025260925300003, 38.622150421100002]
],
},
properties: {
"strokeColor": "#0000FF"
}
}, {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-80.1, 33.9],
[-79.6, 34.916751861599998],
[-85.1, 39.6]
],
},
properties: {
"strokeColor": "#FF0000"
}
}]
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<title>LineString Colors</title>
<div id="map"></div>
I have a list of places in a text box in Google maps. When a person clicks on one of the places in the text box, I want the corresponding marker of that location in Google Maps to bounce. Any ideas on how I can make this work? Right now I am only able to make the marker bounce when I click on the marker itself.
Here is my code:
var Points = [ {
name: 'Duomo-Cathedral',
lat: 43.7732,
long: 11.2560,
url: 'http://www.google.com'
}, {
name: 'Orsanmichele-Church',
lat: 43.770947,
long: 11.254981,
url: 'http://www.google.com'
}, {
name: 'Ponte Vecchio-Old Bridge',
lat: 43.768350,
long: 11.253323,
url: 'http://www.google.com'
}, {
name: 'Galleria delgi Uffizzi-Art Gallery',
lat: 43.768657,
long: 11.255737,
url: 'http://www.google.com'
}, {
name: 'Santa Croce-Church',
lat: 43.768816,
long: 11.262394,
add1: 'Piazza Santa Croce, 16',
add2: ' Florence, Italy 50122',
phone: '+39 055 246 6105',
url: 'https://www.santacroceopera.it/'
}, {
name: 'Palazzo Vecchio-TownHall',
lat: 43.769670,
long: 11.256075,
url: 'https://www.google.com'
}, {
name: 'Piazza della Signoria-OpenSquare',
lat: 43.769725,
long: 11.255474,
url: 'http://www.google.com/'
}, {
name: 'Santa Maria Novella-Church',
lat: 43.774502,
long: 11.249466,
url: 'https://www.google.com'
}, {
name: 'Santa Maria Novella-TrainStation',
lat: 43.776261,
long: 11.248737,
url: 'https://www.google.com'
}, {
name: 'San Lorenzo- ChurchMarket',
lat: 43.774858,
long: 11.254584,
url: 'http://www.google.com'
}
];
var markersArray = ko.observableArray([]);
Points.forEach(populateMarkersArray);
function populateMarkersArray(element) { //, index, array
markersArray.push(element);
}
// Set up a google map
var mapOptions = {
center: { lat: 43.771341,lng: 11.256875},
zoom: 16
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
function initialize() {
Points.forEach(loadMarkers);
var infowindow0 = new google.maps.InfoWindow();
var marker0 = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(function() {
infowindow0.close();
marker0.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
marker0.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker0.setPosition(place.geometry.location);
marker0.setVisible(true);
infowindow0.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow0.open(map, marker0);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function loadMarkers(element) { //, index, array
var myLatlng = new google.maps.LatLng(element.lat,element.long);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: element.name
});
loadInfoWindow(element, marker);
}
function loadInfoWindow(element, marker) {
var contentString = '<div class="strong">' + element.name + '</div><div>' + element.add1 + '</div><div>' + element.add2 + '</div><div>'+ element.phone + '</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
toggleBounce(marker);
});
}
function toggleBounce(marker) {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
function viewModel() {
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Marker Animations</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0; }
#map-canvas { height: 100% }
.place-list {
display: inline-block;
width: 250px;
max-height: 70%;
float: right;
position: absolute;
top: 40px;
right: 6px;
z-index: 5;
overflow-y: auto;
background-color: white;
border: 2px solid grey;
opacity: 0.8;
list-style-type: none;
padding: 20px;
margin: auto;
font-weight: bolder;
border-radius: 25px;
}
</style>
</head>
<body>
<ul class="place-list" data-bind="foreach: Points" >
<li data-bind="text: name, click: $parent.marker" ></li>
</ul>
<div id="map-canvas"></div>
<script type="text/javascript" src="https://maps.googleapis.Com/maps/api/js?key=AIzaSyCPgww-LhtxoQqq2zLI1_gOU1L2XayS-rE"> </script>
<script src="js/lib/knockout-3.2.0.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Thanks for your help,
Max
One of the ways to do it is to use Knockout.js data-binding. In particular, you can use foreach binding to display all your items as a list and apply functions to each of them. Then use click binding to execute functions attached to list items when a user clicks on it. An example of how to use it for list view of places in Google Maps with search function:
HTML:
<h4>Places</h4>
<input type="text" id="my-Input" data-bind="textInput: filter" placeholder="Search for places..">
<div class="scroll" id="my-UL">
<ul data-bind="foreach: visiblePlaces">
<li>
<input data-bind="value: title, click: $parent.zoomToPlace, text: address" type="button" class="btn btn-small btn-link" id="zoomTo">
</li>
</ul>
</div>
JS:
/ ViewModel - provides list view of places, on click zooms map, shows the marker, infowindow, etc.
function viewModel() {
var self = this;
self.places = ko.observableArray(locations);
self.address = ko.observable();
self.title = ko.observable();
self.id = ko.observable();
this.filter = ko.observable();
this.visiblePlaces = ko.computed(function() {
return this.places().filter(function(place) {
if (!self.filter() || place.title.toLowerCase().indexOf(self.filter().toLowerCase()) !== -1)
return place;
});
}, this);
//Zooms to a selected marker and open infowindow
self.zoomToPlace = function() {
// Initialize the geocoder.
var geocoder = new google.maps.Geocoder();
// Get the place.
var address = this.address;
var id = this.id;
// Geocode the address/area entered to get the center. Then, center the map on it and zoom in
geocoder.geocode({
address: address,
}, function(results, status) {
map.setCenter(results[0].geometry.location);
map.setZoom(15);
google.maps.event.trigger(markers[id], 'click');
});
};
}
var vm = new viewModel();
ko.applyBindings(vm);
This will produce a list of places from an array (styles and array aren't shown in the code) and the corresponding marker will open an infowindow and bounce.
For full code, you can look it in my repo: https://github.com/DmitryGrechko/Neighborhood_Map
I'm struggling to find a way to style the infowindows on this map. I've tried suppressing the infowindow by setting suppressInfoWindows: true but that didn't seem to work. Any ideas would be massively appreciated. I've read through a lot of Google docs and a lot of other posts on here and can't find a solution.
<script>
var geocoder;
var map;
var marker;
var layers = [];
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (51.505288, -0.191544);
var myOptions = {
zoom: 15,
disableDefaultUI: true,
styles: [
{
stylers: [
]
},
{
featureType: "poi.park",
stylers: [
{ color: "#aecfae" },
{ saturation: 0 },
{ lightness: 0 },
{ visibility: "simplified" }
]
},
{
featureType: "landscape",
stylers: [
{ color: "#ffffff" },
{ saturation: 0 },
{ lightness: 0 },
{ visibility: "simplified" }
]
},
{
featureType: "road.highway",
elementType: "labels",
stylers: [
{ color: "transparent" },
{ visibility: "off" },
]
},
{
featureType: "water",
elementType: "geometry.fill",
stylers: [
{ color: "#a5bfdd" },
{ visibility: "on" },
]
},
{
featureType: "road",
elementType: "labels",
stylers: [
{ color: "transparent" },
{ visibility: "off" },
]
},
{
featureType: "road",
elementType: "geometry",
stylers: [
{ color: "#e0e0e0" },
{ saturation: 0 },
{ lightness: 0 },
{ visibility: "simplified" }
]
}],
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
marker = new google.maps.Marker({map:map});
layers[0] = new google.maps.KmlLayer('http://www.cid-dev.co.uk/vicarage-phase-2/kml/VicarageGate.kml', {preserveViewport: true});
for (var i = 0; i < layers.length; i++) {
layers[i].setMap(map);
}
layers[1] = new google.maps.KmlLayer('http://www.cid-dev.co.uk/vicarage-phase-2/kml/PrimarySchools-1.kml',
{preserveViewport: true});
layers[2] = new google.maps.KmlLayer('http://www.cid-dev.co.uk/vicarage-phase-2/kml/SecondarySchools-1.kml', {preserveViewport: true});
layers[3] = new google.maps.KmlLayer('http://www.cid-dev.co.uk/vicarage-phase-2/kml/Culture-6.kml', {preserveViewport: true});
layers[4] = new google.maps.KmlLayer('http://www.cid-dev.co.uk/vicarage-phase-2/kml/Hotels-2.kml', {preserveViewport: false});
layers[5] = new google.maps.KmlLayer('http://www.cid-dev.co.uk/vicarage-phase-2/kml/Shopping.kml', {preserveViewport: false});
layers[6] = new google.maps.KmlLayer('http://www.cid-dev.co.uk/vicarage-phase-2/kml/Restaurants.kml', {preserveViewport: false});
for (var i = 1; i < layers.length; i++) {
layers[i].setMap(null);
}
}
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results [0].geometry.location);
marker.setPosition(results [0].geometry.location);
map.setZoom(15);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function toggleLayer(i) {
if(layers[i].getMap() === null) {
layers[i].setMap(map);
}
else {
layers[i].setMap(null);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map_canvas" style="position:absolute; width:100%; height:100%; top:0px; left:0px; right:0px; bottom:0px; z-index:100; background-color:#000;"></div>
Suppress the automatic info window generation, and use the click event to manually handle the data.
Here's an example that is removing the target="_blank" attribute from the info window links: http://people.missouristate.edu/chadkillingsworth/mapsexamples/removekmllinktargets.js
You can try adding a method like this to all your markers.
// generalized click handler
function addClickHandler(item, content, position) {
google.maps.event.addListener(item, 'click', function () {
infoWindow.close();
infoWindow.setContent(content);
infoWindow.setPosition(position);
infoWindow.open(map);
});
}
When I am styling with KML anything passed through in <[CDATA tag is formatted. So adding within the cdata is allowed.
Also heres an example from GOOGLE
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/examples/example.html
Base on this http://jsfiddle.net/kaiser/wzcst/light/ example, but the marker in circle is not accurate, when the marker is outside circle and near to circle it is consider inside the circle which is not wanted.
Is there any other idea?
code snippet (from linked fiddle):
window.onload = function init() {
var
contentCenter = '<span class="infowin">Center Marker (draggable)</span>',
contentA = '<span class="infowin">Marker A (draggable)</span>',
contentB = '<span class="infowin">Marker B (draggable)</span>';
var
latLngCenter = new google.maps.LatLng(37.081476, -94.510574),
latLngCMarker = new google.maps.LatLng(37.0814, -94.5105),
latLngA = new google.maps.LatLng(37.2, -94.1),
latLngB = new google.maps.LatLng(38, -93),
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: latLngCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}),
markerCenter = new google.maps.Marker({
position: latLngCMarker,
title: 'Location',
map: map,
draggable: true
}),
infoCenter = new google.maps.InfoWindow({
content: contentCenter
}),
markerA = new google.maps.Marker({
position: latLngA,
title: 'Location',
map: map,
draggable: true
}),
infoA = new google.maps.InfoWindow({
content: contentA
}),
markerB = new google.maps.Marker({
position: latLngB,
title: 'Location',
map: map,
draggable: true
}),
infoB = new google.maps.InfoWindow({
content: contentB
})
// exemplary setup:
// Assumes that your map is signed to the var "map"
// Also assumes that your marker is named "marker"
,
circle = new google.maps.Circle({
map: map,
clickable: false,
// metres
radius: 100000,
fillColor: '#fff',
fillOpacity: .6,
strokeColor: '#313131',
strokeOpacity: .4,
strokeWeight: .8
});
// attach circle to marker
circle.bindTo('center', markerCenter, 'position');
var
// get the Bounds of the circle
bounds = circle.getBounds()
// Note spans
,
noteA = jQuery('.bool#a'),
noteB = jQuery('.bool#b');
noteA.text(bounds.contains(latLngA));
noteB.text(bounds.contains(latLngB));
// get some latLng object and Question if it's contained in the circle:
google.maps.event.addListener(markerCenter, 'dragend', function() {
latLngCenter = new google.maps.LatLng(markerCenter.position.lat(), markerCenter.position.lng());
bounds = circle.getBounds();
noteA.text(bounds.contains(latLngA));
noteB.text(bounds.contains(latLngB));
});
google.maps.event.addListener(markerA, 'dragend', function() {
latLngA = new google.maps.LatLng(markerA.position.lat(), markerA.position.lng());
noteA.text(bounds.contains(latLngA));
});
google.maps.event.addListener(markerB, 'dragend', function() {
latLngB = new google.maps.LatLng(markerB.position.lat(), markerB.position.lng());
noteB.text(bounds.contains(latLngB));
});
google.maps.event.addListener(markerCenter, 'click', function() {
infoCenter.open(map, markerCenter);
});
google.maps.event.addListener(markerA, 'click', function() {
infoA.open(map, markerA);
});
google.maps.event.addListener(markerB, 'click', function() {
infoB.open(map, markerB);
});
google.maps.event.addListener(markerCenter, 'drag', function() {
infoCenter.close();
noteA.html("draggin…");
noteB.html("draggin…");
});
google.maps.event.addListener(markerA, 'drag', function() {
infoA.close();
noteA.html("draggin…");
});
google.maps.event.addListener(markerB, 'drag', function() {
infoB.close();
noteB.html("draggin…");
});
};
body {
margin: 0;
padding: 0
}
html,
body,
#map {
height: 100%;
font-family: Arial, sans-serif;
font-size: .9em;
color: #fff;
}
#note {
text-align: center;
padding: .3em;
10px;
background: #009ee0;
}
.bool {
font-style: italic;
color: #313131;
}
.info {
display: inline-block;
width: 40%;
text-align: center;
}
.infowin {
color: #313131;
}
#title,
.bool {
font-weight: bold;
}
<script src="http://maps.googleapis.com/maps/api/js"></script>
<div id="note"><span id="title">»Inside the circle?«</span>
<hr /><span class="info">Marker <strong>A</strong>: <span id="a" class="bool"></span></span>←♦→ <span class="info">Marker <strong>B</strong>: <span id="b" class="bool"></span></span>
</div>
<div id="map">test</div>
A google.maps.LatLngBounds is a rectangle. You need a polygon "contains" function. For a circle this can be reduced to testing whether the point is less than the radius away from the center.
Example
code snippet:
window.onload = function init() {
var
contentCenter = '<span class="infowin">Center Marker (draggable)</span>',
contentA = '<span class="infowin">Marker A (draggable)</span>',
contentB = '<span class="infowin">Marker B (draggable)</span>';
var
latLngCenter = new google.maps.LatLng(37.081476, -94.510574),
latLngCMarker = new google.maps.LatLng(37.0814, -94.5105),
latLngA = new google.maps.LatLng(37.2, -94.1),
latLngB = new google.maps.LatLng(38, -93),
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: latLngCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}),
markerCenter = new google.maps.Marker({
position: latLngCMarker,
title: 'Center of Circle',
map: map,
draggable: true
}),
infoCenter = new google.maps.InfoWindow({
content: contentCenter
}),
markerA = new google.maps.Marker({
position: latLngA,
title: 'A',
map: map,
label: "A",
draggable: true
}),
infoA = new google.maps.InfoWindow({
content: contentA
}),
markerB = new google.maps.Marker({
position: latLngB,
title: 'B',
map: map,
label: "B",
draggable: true
}),
infoB = new google.maps.InfoWindow({
content: contentB
})
// exemplary setup:
// Assumes that your map is signed to the var "map"
// Also assumes that your marker is named "marker"
,
circle = new google.maps.Circle({
map: map,
clickable: false,
// metres
radius: 100000,
fillColor: '#fff',
fillOpacity: .6,
strokeColor: '#313131',
strokeOpacity: .4,
strokeWeight: .8
});
// attach circle to marker
circle.bindTo('center', markerCenter, 'position');
var
// get the Bounds of the circle
bounds = circle.getBounds()
// Note spans
,
noteA = jQuery('.bool#a'),
noteB = jQuery('.bool#b');
noteA.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerA.getPosition(), markerCenter.getPosition())));
noteB.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerB.getPosition(), markerCenter.getPosition())));
// get some latLng object and Question if it's contained in the circle:
google.maps.event.addListener(markerCenter, 'dragend', function() {
latLngCenter = markerCenter.position;
noteA.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerA.getPosition(), markerCenter.getPosition())));
noteB.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerB.getPosition(), markerCenter.getPosition())));
});
google.maps.event.addListener(markerA, 'dragend', function() {
latLngA = markerA.position;
noteA.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerA.getPosition(), markerCenter.getPosition())));
});
google.maps.event.addListener(markerB, 'dragend', function() {
latLngB = markerB.position;
noteB.text((100000 > google.maps.geometry.spherical.computeDistanceBetween(markerB.getPosition(), markerCenter.getPosition())));
});
google.maps.event.addListener(markerCenter, 'click', function() {
infoCenter.open(map, markerCenter);
});
google.maps.event.addListener(markerA, 'click', function() {
infoA.open(map, markerA);
});
google.maps.event.addListener(markerB, 'click', function() {
infoB.open(map, markerB);
});
google.maps.event.addListener(markerCenter, 'drag', function() {
infoCenter.close();
noteA.html("draggin…");
noteB.html("draggin…");
});
google.maps.event.addListener(markerA, 'drag', function() {
infoA.close();
noteA.html("draggin…");
});
google.maps.event.addListener(markerB, 'drag', function() {
infoB.close();
noteB.html("draggin…");
});
};
body {
margin: 0;
padding: 0
}
html,
body,
#map {
height: 100%;
font-family: Arial, sans-serif;
font-size: .9em;
color: #fff;
}
#note {
text-align: center;
padding: .3em;
10px;
background: #009ee0;
}
.bool {
font-style: italic;
color: #313131;
}
.info {
display: inline-block;
width: 40%;
text-align: center;
}
.infowin {
color: #313131;
}
#title,
.bool {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="note"><span id="title">»Inside the circle?«</span>
<hr /><span class="info">Marker <strong>A</strong>: <span id="a" class="bool"></span></span>←♦→ <span class="info">Marker <strong>B</strong>: <span id="b" class="bool"></span></span>
</div>
<div id="map">test</div>