Using gmaps.js to place markers from geoJSON file - javascript

I need to, using gmaps.js, grab marker information from a .json file and display the marker locations on my local html page.
I have been able to do this successfully with the standard Google Maps Platform API using the example given here:
https://developers.google.com/maps/documentation/javascript/importing_data
My geojson file is in the same format as the one in the example above.
However I would like to use gmaps.js because of its simplicity and ease of use.
How can the above code be adapted and used with gmaps.js?
Here is my very basic code so far:
var mapObj = new GMaps({
el: '#map',
lat: 30.267283,
lng: -90.554560,
zoom: 2,
minZoom: 2
})
/*attempting to place markers from geojson file*/
/*managed to add markers manually*/
mapObj.addMarker({
lat: 30.267283,
lng: -90.554560,
title: 'Marker with InfoWindow',
infoWindow: {
content: '<p>HI!</p>'
},
click: function(e) {
mapObj.map.panTo(e.position);
}
});
I have attempted to use: https://hpneo.dev/gmaps/examples/json.html
However my webpage seems to result in a blank white screen.

The gmaps example on Working with JSON works fine; you just need to modify it based off of your own JSON file. If it looks like the one from Google's documentation then you can just load it directly with getJSON like gmaps.js does.
Take a look at this jsbin for demonstration and guidance. Full code below. Hope it helps!
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key="></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.25/gmaps.js"></script>
<script>
var map;
function loadResults(data) {
var markers_data = [];
for (var i = 0; i < data.features.length; i++) {
var coords = data.features[i].geometry.coordinates;
markers_data.push({
lat: coords[1],
lng: coords[0],
infoWindow: {
content: '<p>HI!</p>'
},
click: function(e) {
map.map.panTo(e.position);
}
});
}
map.addMarkers(markers_data);
}
$(document).on('click', '.pan-to-marker', function(e) {
e.preventDefault();
var position, lat, lng, $index;
$index = $(this).data('marker-index');
position = map.markers[$index].getPosition();
lat = position.lat();
lng = position.lng();
map.setCenter(lat, lng);
});
$(document).ready(function() {
map = new GMaps({
el: '#map',
lat: 30.267283,
lng: -90.554560,
zoom: 2,
minZoom: 2
});
map.on('marker_added', function(marker) {
var index = map.markers.indexOf(marker);
if (index == map.markers.length - 1) {
map.fitZoom();
}
});
var xhr = $.getJSON('https://api.myjson.com/bins/11fqjv');
xhr.done(loadResults);
});
</script>
</body>
</html>

Related

How can I mark coordinates from a Google sheet on a sidebar map? -- Map api

Here's my situation: I have a google sheet of coordinates that I want to map on a simple map. This map I want to put on a sidebar within google sheets. It will get more complex as I go but I'm struggling with the basics.
So I want to import the coordinates of C2:D2 into my HTML so I used this: google.script.run.withSuccessHandler(initMap).selectAddress().
It seems to work for most things but when I use it for the coordinates of the marker, nothing no marker shows up. If I replace
"var lat = CoordArray[0]; var lng = CoordArray[1];"
with
"var lat =51.0366961; var lng = -114.0744921;"
in the HTML, the marker shows up.
Even if I make "var CoordArray= [51.0366961,-114.0744921]" in the JS code, the marker still doesn't show. So the problem has something to do with transferring the information between the two pages.
I just want an interactive map sidebar that's based on coordinates from the sheet that I can kind of understand and modify.
So my JS code page looks like this:
function mapSidebar(){
var html = HtmlService.createHtmlOutputFromFile('Map.html')
.setTitle("Map Sidebar");
SpreadsheetApp.getUi().showSidebar(html);
};
//------------------------------------------------------------------------------------------------
function selectAddress(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("maps?");
var CoordArray = sheet.getRange("C2:D2").getValues(); // C2:D2 = 51.0366961,-114.0744921
return CoordArray;
};
//----------------------------------------------------------------------------------------------
My Html page (Map.html) looks like this:
and yes, I replaced put my API key in the 'https://maps.googleapis.com/' link
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap(CoordArray) {
var lat = CoordArray[0];
var lng = CoordArray[1];
var markerPosition = {lat: lat,lng: lng}
var map = new google.maps.Map(document.getElementById('map'), {
center:{lat: 51.0366961,lng: -114.0744921},
zoom: 8,
});
var marker = new google.maps.Marker({position: markerPosition, map: map});
}
google.script.run.withSuccessHandler(initMap).selectAddress();
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY=initMap">
</script>
</body>
</html>
It appears you may be having an issue with the Range.getValues() method in your code. This method returns a 2D array indexed by rows, then by columns.
Try in your initMap() function to get the "lat" and "lng" like so:
function initMap(CoordArray) {
var lat = CoordArray[0][0];
var lng = CoordArray[0][1];
var markerPosition = {
lat: lat,
lng: lng
}
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 51.0366961,
lng: -114.0744921
},
zoom: 8,
});
var marker = new google.maps.Marker({
position: markerPosition,
map: map
});
}
References:
Apps script docs Range.getValues()

Adding multiple markers with Google Maps API [duplicate]

This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 4 years ago.
I am trying to use Google maps API for a website and I can't seem to get multiple locations to populate like Google has it in their example.
Could anyone please let me know what I need to add to get 11 markers to show up that will give a description of what I want.
I can see that Google has multiple locations giving a quick description of what they are.
PS: I already have a key I just need to know how to include "X" number of markers with a description attached.
Attached is the link to googles example:
Google Maps API
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* 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;
}
</style>
<script>
// 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;
var infowindow;
function initMap() {
var pyrmont = {lat: -33.867, lng: 151.195};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
</body>
</html>
You need to try this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
/* 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;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

How to set gmaps to open at my location?

Trying to get gmaps to open at my location but its not working for me:
Edited: there was supposed to be nothing at the lat and lng, also added the div where this map is presented. I thought I could create a map with no coordinates, but have it go to my location right after creation using the geolocation function. How can i write this so that the map is created at my location without hardcoding the coordinates?
<div id="outputMap"></div>
<script>
var map;
map = new GMaps({
div: '#outputMap',
lat: 0,
lng: 0,
});
GMaps.geolocate({
function(position) {
map.setCenter(position.coords.latitude, position.coords.longitude);
}});
map.zoomOut();
When using the official JS API, an initial zoom value is required:
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<div id="map"></div>
<script>
var map = new google.maps.Map(document.getElementById('map'), {zoom: 14});
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
});
</script>
</body>
</html>

is it possible to apply some condition to geojson file/layer before uploading on google map?

i have a geojson file having some data. i can load this file on google map successfully. But actually i want to filter it before showing on google map that is to locate only those points on google map from geojson which fulfilling some condition
testLayer = new google.maps.Data();
testLayer.loadGeoJson('geojson/file/path/test.geojson');
testLayer.setMap(map);
That's supported by Google Maps Data API, the following example demonstrates how to clear two polygons (letter o in Google word)
$(function () {
initMap();
});
function initMap() {
var map = new google.maps.Map(document.getElementById('div_map'), {
center: {
lat: -25.0323575,
lng: 115.2244976
},
zoom: 3,
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var layer = new google.maps.Data();
layer.addListener('addfeature', processData);
layer.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json');
layer.setMap(map);
}
function processData(o) {
var f = o.feature;
var geometry = f.getGeometry();
if(o.feature.getProperty('letter') == "o"){
o.feature.setGeometry(null);
}
}
#div_map {
height: 240px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="div_map"></div>

Google maps - storing application-defined data in path

In my app I want to store application-defined data on each latLng in a path.
I have got this to work using the code example below, but I would like to know whether this is an undocumented fluke that just 'happens' to work and could get broken in the future, or is it perfectly valid code that should always work?
In short, is 'getPath' guaranteed to return the same latLng objects that were passed in, or can it pass back new ones with the same lat and the same lng but anything else that google doesn't care about might not still be there?
Thanks for any assistance
Click on the line, and it should alert "one two three".
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.0, -1.5),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var polyline = new google.maps.Polyline({
map: map,
strokeColor: "blue",
strokeThicknedss: 2
});
polyline.setPath([
getLatLng(51.9, -1.4, "one"),
getLatLng(52.0, -1.5, "two"),
getLatLng(52.0, -1.6, "three")
]);
google.maps.event.addListener(polyline, "click", function() {
var path = this.getPath().getArray();
var datas = [];
for(var i = 0; i < path.length; i++) {
var ll = path[i];
datas.push(ll.data);
}
alert(datas.join("\n"));
});
}
function getLatLng(lat, lng, data) {
var ll = new google.maps.LatLng(lat, lng);
ll.data = data;
return ll;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
Well according to the docs getPath() 'retrieves the first path'. And you've just set the path using setPath()... I'm not sure Google are going to mess with that data; your approach seems sound to me.
I found that the best way for storing polylines is to use Google's encoding function in the geometry library.
var polylineToStore = google.maps.geometry.encoding.encodePath(polyline.getPath());
This sets the polylineToStore variable to a string. When you want to reuse that encoded polyline you only need to decode it:
polyline.setPath(google.maps.geometry.encoding.decodePath(polylineToStore))
https://developers.google.com/maps/documentation/javascript/geometry#Encoding

Categories