Add marker on geojson data layer in google maps - javascript

I have loaded geojson layer to google maps using the following code
map.data.loadGeoJson(
'http://localhost/pssp/assets/geojson/Empanel_Area_2019.geojson');
map.data.setStyle({
fillColor: 'red',
strokeColor: 'red',
strokeWeight: 1
});
)
When I try to add a marker on the data layer on the click event it will get added outside the data layer but not inside. how can I add a marker in side the polygons in the data layer.
I used the following code to add a marker on click event
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}

Add a click listener to the DataLayer as well.
map.data.addListener('click', function(event) {
placeMarker(event.latLng);
});
proof of concept fiddle
code snippet:
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#info-box {
background-color: white;
border: 1px solid black;
bottom: 30px;
height: 20px;
padding: 10px;
position: absolute;
left: 30px;
}
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: -28,
lng: 137
}
});
// Load GeoJSON.
map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');
// Add some style.
map.data.setStyle(function(feature) {
return /** #type {google.maps.Data.StyleOptions} */ ({
fillColor: feature.getProperty('color'),
strokeWeight: 1
});
});
google.maps.event.addListener(map, 'click', function(event) {
console.log("on map:" + event.latLng.toUrlValue(6));
placeMarker(event.latLng);
});
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}
// Set click event for each feature.
map.data.addListener('click', function(event) {
console.log("on polygon:" + event.latLng.toUrlValue(6));
placeMarker(event.latLng);
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

Related

Does Google Maps still support InfoBox?

I am looking to create a custom infoWindow in google maps and I believe creating an infoBox is a way to do this. However, I don't see any documentation or reference to infoBox on google map's documentation. Is this feature deprecated? Should I be using customized popup instead?
The InfoBox library was never part of the Google Maps Javascript API v3. It is a third party library and is still available on GitHub.
https://github.com/googlemaps/v3-utility-library/tree/master/archive/infobox
Note: it is also available in my GitHub account:
https://github.com/geocodezip/v3-utility-library/tree/master/archive/infobox
code snippet (basic example):
function initialize() {
var secheltLoc = new google.maps.LatLng(49.47216, -123.76307);
var myMapOptions = {
zoom: 15
,center: secheltLoc
,mapTypeId: google.maps.MapTypeId.ROADMAP
};
var theMap = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);
var marker = new google.maps.Marker({
map: theMap,
draggable: true,
position: new google.maps.LatLng(49.47216, -123.76307),
visible: true
});
var boxText = document.createElement("div");
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
boxText.innerHTML = "City Hall, Sechelt<br>British Columbia<br>Canada";
var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-140, 0)
,zIndex: null
,boxStyle: {
background: "url('tipbox.gif') no-repeat"
,opacity: 0.75
,width: "280px"
}
,closeBoxMargin: "10px 2px 2px 2px"
,closeBoxURL: "https://www.google.com/intl/en_us/mapfiles/close.gif"
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
};
google.maps.event.addListener(marker, "click", function (e) {
ib.open(theMap, this);
});
var ib = new InfoBox(myOptions);
ib.open(theMap, marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#map_canvas {
width: 100%;
height: 100%;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library#master/archive/infobox/src/infobox.js"></script>
<div id="map_canvas"></div>
<p>
This example shows the "traditional" use of an InfoBox as a replacement for an InfoWindow.

Google Maps MarkerCluster API: How to get clusters outside of screen's view?

I have a webpage that uses Google maps and the MarkerCluster API.
I need to be able to get all of the clusters on the map at a given zoom level. Take this code for example:
//Where the center of the screen will be
var center = new google.maps.LatLng(37.4419, -122.1419);
var options = {
'zoom': 13,
'center': center,
//Google map type
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
//Create the google map
var map = new google.maps.Map(document.getElementById("map"), options);
//Create the marker clusters, where markers is an array of lat and longs
var mc = new MarkerClusterer(map, markers);
//Print all of the clusters at zoom level 13
console.log(mc.getTotalClusters());
The problem is if there are 10 clusters at zoom level 13, but only 7 are inside of my screen's bounds, then the above code would only print out 7. I need a way to get access to all clusters, even if they're not on the screen.
Simple example of how the MarkerClusterer works:
https://googlemaps.github.io/js-marker-clusterer/examples/simple_example.html
Here are some references to the MarkerCluster API:
https://googlemaps.github.io/js-marker-clusterer/docs/reference.html
https://googlemaps.github.io/js-marker-clusterer/docs/examples.html
https://developers.google.com/maps/articles/toomanymarkers
Indeed, getTotalClusters function returns the number of clusters only for markers visible within a current viewport.
One option to get the total amount of clusters would be to disable the checking whether the marker is located within a current viewport by overriding the function that creates clusters:
MarkerClusterer.prototype.createClusters_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, marker; marker = this.markers_[i]; i++) {
//if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!marker.isAdded) {
this.addToClosestCluster_(marker);
}
}
};
Working example
MarkerClusterer.prototype.createClusters_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, marker; marker = this.markers_[i]; i++) {
//if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
if (!marker.isAdded) {
this.addToClosestCluster_(marker);
}
}
};
function initMap(data) {
var center = new google.maps.LatLng(59.339025,18.065818);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = [];
for (var i = 0; i < data.photos.length; i++) {
var dataPhoto = data.photos[i];
var latLng = new google.maps.LatLng(dataPhoto.latitude,dataPhoto.longitude);
var marker = new google.maps.Marker({
position: latLng
});
markers.push(marker);
}
markerCluster = new MarkerClusterer(map, markers, { imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m' });
google.maps.event.addListenerOnce(map, 'idle', function(){
console.log("Total number of clusters: " + markerCluster.getTotalClusters());
});
}
google.maps.event.addDomListener(window, 'load',
function(){
$.getJSON("https://gist.githubusercontent.com/vgrem/fb601469049c4be809ad4ea4bbcdc381/raw/data.json")
.success(function(data) {
initMap(data);
});
});
body {
margin: 0;
padding: 10px 20px 20px;
font-family: Arial;
font-size: 16px;
}
#map-container {
padding: 6px;
border-width: 1px;
border-style: solid;
border-color: #ccc #ccc #999 #ccc;
-webkit-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
-moz-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
box-shadow: rgba(64, 64, 64, 0.1) 0 2px 5px;
width: 600px;
}
#map {
width: 600px;
height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://googlemaps.github.io/js-marker-clusterer/src/markerclusterer.js"></script>
<div id="map-container"><div id="map"></div></div>
Plunker

Keep marker/pin in the middle of the map while dragging

I want the marker/pin to scroll around and be in the center of the map while the user is dragging around the map. I have a simple jsfiddle (http://jsfiddle.net/upsidown/5xd1Lbpc/6/) where the pin will drop to the center of the map when the user stops dragging, but I want the pin to move with the dragging.
Google Maps JS
var center = new google.maps.LatLng(-33.013803, -71.551498);
var map = new google.maps.Map(document.getElementById('mapBox'), {
zoom: 18,
center: center,
mapTypeId: google.maps.MapTypeId.HYBRID
});
var myMarker = new google.maps.Marker({
position: center,
draggable: true,
map: map
});
google.maps.event.addListener(myMarker, 'dragend', function () {
map.setCenter(this.getPosition()); // Set map center to marker position
updatePosition(this.getPosition().lat(), this.getPosition().lng()); // update position display
});
google.maps.event.addListener(map, 'dragend', function () {
myMarker.setPosition(this.getCenter()); // set marker position to map center
updatePosition(this.getCenter().lat(), this.getCenter().lng()); // update position display
});
function updatePosition(lat, lng) {
document.getElementById('dragStatus').innerHTML = '<p> Current Lat: ' + lat.toFixed(4) + ' Current Lng: ' + lng.toFixed(4) + '</p>';
}
HTML
<div id='mapBox'></div>
Any ideas or thoughts on how to do this?
JSFiddle
To reduce flicker, you can put an absolutely positioned marker over top of the map directly in the center. Then you can use getCenter() to retrieve the actual position on the map.
#wrapper {
position: relative;
display: inline-block;
}
#mapBox {
width: 400px;
height: 300px;
}
#marker {
position: absolute;
top: calc(50% - 40px);
left: calc(50% - 40px);
height: 80px;
width: 80px;
border: 3px solid blue;
border-radius: 50%;
background-color: rgba(30,144,255,0.5);
box-sizing: border-box;
pointer-events: none;
}
HTML:
<div id="wrapper">
<div id="mapBox"></div>
<div id="marker"></div>
</div>
<div id="dragStatus"></div>
JS:
var center = new google.maps.LatLng(-33.013803, -71.551498);
var map = new google.maps.Map(document.getElementById('mapBox'), {
zoom: 18,
center: center,
mapTypeId: google.maps.MapTypeId.HYBRID
});
google.maps.event.addListener(map, 'drag', function() {
loc(map);
});
google.maps.event.addListener(myMarker, 'dragend', function () {
loc(map);
});
function loc(map) {
var x = map.getCenter();
document.getElementById('dragStatus').innerHTML = x.lat() + ', ' + x.lng();
}
Other Useful Answers:
Is there a way to Fix a Google Maps Marker to the Center of its Map always?
add this
google.maps.event.addListener(map, 'drag', function () {
myMarker.setPosition(this.getCenter()); // set marker position to map center
updatePosition(this.getCenter().lat(), this.getCenter().lng()); // update position display
});
see http://jsfiddle.net/gbqqzonr/
//Dragable Marker In Google Map....
var center = new google.maps.LatLng(-33.013803, -71.551498);
var map = new google.maps.Map(document.getElementById('mapBox'), {
zoom: 18,
center: center,
mapTypeId: google.maps.MapTypeId.HYBRID
});
var myMarker = new google.maps.Marker({
position: center,
draggable: true,
map: map
});
google.maps.event.addListener(myMarker, 'dragend', function () {
map.setCenter(this.getPosition()); // Set map center to marker position
updatePosition(this.getPosition().lat(), this.getPosition().lng()); // update position display
});
google.maps.event.addListener(map, 'drag', function () {
myMarker.setPosition(this.getCenter()); // set marker position to map center
updatePosition(this.getCenter().lat(), this.getCenter().lng()); // update position display
});
google.maps.event.addListener(map, 'dragend', function () {
myMarker.setPosition(this.getCenter()); // set marker position to map center
updatePosition(this.getCenter().lat(), this.getCenter().lng()); // update position display
});
function updatePosition(lat, lng) {
document.getElementById('dragStatus').innerHTML = '<p> Current Lat: ' + lat.toFixed(4) + ' Current Lng: ' + lng.toFixed(4) + '</p>';
}

How do I re position the google map infowindow

How do I re position the infowindow in a google map?
I would like the window to open under the marker with the little indent facing up towards to the marker.
Here is my code I thought the pixeloffset would be the option to change but not sure. When I adjust the y to 70 it shows up below the marker but how do I change the indent to flip around?
$infowindow = new google.maps.InfoWindow({
content: "Drag the map to re-center location",
pixelOffset: new google.maps.Size(0, 70), // want the window to open underneathe with the indent facing up
});
The behavior you are looking for is not (currently) supported by the native google.maps.InfoWindow. You can create a feature request in the issue tracker for the Google Maps JavaScript API v3.
For something that would work now, InfoBox might do what you are looking for, see the example in the documentation
code snippet:
function initialize() {
var secheltLoc = new google.maps.LatLng(49.47216, -123.76307);
var myMapOptions = {
zoom: 15,
center: secheltLoc,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var theMap = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);
var marker = new google.maps.Marker({
map: theMap,
draggable: true,
position: new google.maps.LatLng(49.47216, -123.76307),
visible: true
});
var boxText = document.createElement("div");
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: white; padding: 5px; text-align: center;";
boxText.innerHTML = "Drag the map to re-center location";
var myOptions = {
content: boxText,
disableAutoPan: false,
maxWidth: 0,
pixelOffset: new google.maps.Size(-140, 0),
zIndex: null,
boxStyle: {
background: "url('http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/examples/tipbox.gif') no-repeat",
opacity: 0.75,
width: "280px"
},
closeBoxMargin: "10px 2px 2px 2px",
closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
infoBoxClearance: new google.maps.Size(1, 1),
isHidden: false,
pane: "floatPane",
enableEventPropagation: false
};
google.maps.event.addListener(marker, "click", function(e) {
ib.open(theMap, this);
});
var ib = new InfoBox(myOptions);
ib.open(theMap, marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<div id="map_canvas" style="width: 100%; height: 400px"></div>
<p>
This example shows the "traditional" use of an InfoBox as a replacement for an InfoWindow.

Google Maps API - Only One JS Script Displays on Map

I answered my question with help from a friend - labels and building polygons with pop ups now display.
The code uses an external GeoJSON with two building coordinates, values for colors and building names. The GeoJSON is used to draw the buidling polygons, and populate infoBox window.
The labels are blank window boxes with coordinates and text hard coded. There are other examples of this on Stack Overflow, however, I was having trouble getting both functions to work. Thanks to everyone who helped.
<!DOCTYPE html>
<html>
<head>
<title>UT Campus Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 90%;
padding: 10px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script>
// global variable
var map;
var mapData;
var dataURL = 'https://googledrive.com/host/0B9SE53Gvj0AsR3hyUDJ4Nk9ybG8/Bld.json';
var infoWindow = new google.maps.InfoWindow();
var colors = ["#9295ca", "#076bb6", "#e66665", "#666", "#333", "#456789"];
// create the map when the page loads
function initialize() {
var mapOptions = {
zoom: 16,
center: new google.maps.LatLng(30.284, -97.7325)
};
// build the map
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// get the data and draw the polygons
$.getJSON( dataURL, function( data ) {
loadGeoJSON(data);
});
// add colors
stylePolygons();
// add click listeners with info boxes
addClickListeners();
// finally add labels
addLabels();
};
// fetch the geojson data from the server
function loadGeoJSON (data) {
console.log(data);
map.data.addGeoJson(data,{idPropertyName:"id"});
};
// assign colors based on value property of each feature
function stylePolygons () {
map.data.setStyle(function(feature) {
var value = feature.getProperty('value');
var color = colors[value];
return {
fillColor: color,
strokeWeight: 1
};
});
};
//listen for click events
function addClickListeners () {
map.data.addListener('click', function(event) {
//show an infowindow on click
infoWindow.setContent('<div style="line-height:1.35;overflow:hidden;white-space:nowrap;"> <b>'+event.feature.getProperty("bldAbbrev") +"</b>"+"</br>" + event.feature.getProperty("GoogInfoWi") +"<br/>" + event.feature.getProperty("addressStr") +"</div>");
var anchor = new google.maps.MVCObject();
anchor.set("position",event.latLng);
infoWindow.open(map,anchor);
});
};
function buildMarkers(map, markerData) {
var newMarkers = [],
marker;
var blankMarker = {
path: 'M 0,0,0 z',
fillColor: 'yellow',
fillOpacity: 0.8,
scale: 0,
strokeColor: 'white',
strokeWeight: 4
};
for(var i=0; i<markerData.length; i++) {
marker = new google.maps.Marker({
map: map,
icon: blankMarker,
draggable: true,
position: markerData[i].latLng,
visible: true
}),
boxText = document.createElement("div"),
//these are the options for all infoboxes
infoboxOptions = {
content: boxText,
disableAutoPan: false,
maxWidth: 0,
pixelOffset: new google.maps.Size(40, 0),
zIndex: null,
boxStyle: {
background: "url('http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/examples/tipbox.gif') no-repeat",
opacity: 1,
width: "24px"
},
closeBoxMargin: "12px 4px 2px 2px",
closeBoxURL: "",
infoBoxClearance: new google.maps.Size(0, 0),
isHidden: false,
pane: "floatPane",
enableEventPropagation: false
};
newMarkers.push(marker);
//define the text and style for all infoboxes
boxText.style.cssText = "margin-top: 8px; background:#0xFFFFFF; color:#333; font-family:Arial; font-size:24px; padding: 0px; border-radius:0px; -webkit-border-radius:0px; -moz-border-radius:0px;";
boxText.innerHTML = markerData[i].label;
//Define the infobox
newMarkers[i].infobox = new InfoBox(infoboxOptions);
//Open box when page is loaded
newMarkers[i].infobox.open(map, marker);
}
return newMarkers;
};
function addLabels () {
var markerInfoArray =
[
{
latLng: new google.maps.LatLng(30.2848878, -97.7362857),
label:"SAC"
},
{
latLng: new google.maps.LatLng(30.2819835, -97.7404576),
label:"ATT"
}
];
var markerArray = buildMarkers(map, markerInfoArray);
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
I replaced the original question with the working code. Sorry for poor formatting and procedure, this was my first question.

Categories

Resources