Google Sites + Maps Javascript API + HTML5 Geolocation - google-maps-api-3

I'm trying to implement a map with a route that has a waypoint and a dynamic origin within a Google Site. I'd like to set the origin based on the user's location who access the Google Sites and I'm using the HTML5 Geolocation API to retrieve the user's geolocation. However, I'm not able to retrieve properly the user's geolocation.
Here you will find the code I'm currently implementing.
<!DOCTYPE html>
<html>
<head>
<title>PATH A</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<style type="text/css">
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: 37.132, lng: 13.869 },
});
directionsRenderer.setMap(map);
const onChangeHandler = function () {
calculateAndDisplayRoute(directionsService, directionsRenderer);
};
window.onload = onChangeHandler;
}
function setPosition(position){
currentOrigin = {};
currentOrigin.lat = position.coords.latitude;
currentOrigin.lng = position.coord.longitude;
}
function calculateAndDisplayRoute(directionsService, directionsRenderer){
let currentOrigin = new google.maps.LatLng(37.081, 14.214);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition);
} else {
// Browser doesn't support Geolocation
console.log("Browser does not support geolocation");
}
const waypts = [];
waypts.push({
location: { lat: 37.261, lng: 13.588},
stopover: true
});
directionsService.route({
origin: currentOrigin,
destination: {
lat: 37.314 , lng: 13.576
},
optimizeWaypoints: false,
waypoints: waypts,
travelMode: google.maps.TravelMode.DRIVING
}, (response, status) => {
if(status === "OK" && response) {
directionsRenderer.setDirections(response);
} else {
console.log("An error occurred: " + status);
}
});
}
</script>
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=*********&callback=initMap&libraries=&v=weekly"
async
></script>
</body>
</html>
Is the Geolocation API somehow blocked by the Google Sites' policies? If so, is there any other way to set up a dynamic origin? The desired solution is to have a map on the site that has a route with a specific waypoint.
Thanks in advance for your attention.

So a couple of things first I think you have a typo in your setPosition callback function the longitude should be position.coords.longitude . Also you need to set the center of the google maps object when the navigator returns a lat and lng. Right now currentOrigin is out of scope of the map and never is able to update. One thing you could possibly try is passing a reference of your map object to calculateAndDisplayRoute and setting the map's location in the setPosition callback.
Try this:
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: 37.132, lng: 13.869 },
});
directionsRenderer.setMap(map);
const onChangeHandler = function () {
calculateAndDisplayRoute(directionsService, directionsRenderer, map);
};
window.onload = onChangeHandler;
}
function setPosition(position, map){
currentOrigin = {};
map.setCenter({ lat : position.coords.latitude, lng: position.coords.longitude });
}
function calculateAndDisplayRoute(directionsService, directionsRenderer, map){
let currentOrigin = new google.maps.LatLng(37.081, 14.214);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
setPosition(position, map);
});
} else {
// Browser doesn't support Geolocation
console.log("Browser does not support geolocation");
}
const waypts = [];
waypts.push({
location: { lat: 37.261, lng: 13.588},
stopover: true
});
directionsService.route({
origin: currentOrigin,
destination: {
lat: 37.314 , lng: 13.576
},
optimizeWaypoints: false,
waypoints: waypts,
travelMode: google.maps.TravelMode.DRIVING
}, (response, status) => {
if(status === "OK" && response) {
directionsRenderer.setDirections(response);
} else {
console.log("An error occurred: " + status);
}
});
}
I passed the map object through to the callback so that setCenter could be called on the navigators position.

Related

can I use geofencing in a fremium account, i'm having issues uploading a geofence to the server

I created a free account with here technologies as I need to create geofences around traffic signals and check if any of my devices entered the geofences and trigger a action.
var platform = new H.service.Platform({
'apikey': 'apikeyhere' // here i used the javascript maps api key
});
var maptypes = platform.createDefaultLayers();
var lineString = new H.geo.LineString()
lineString.pushPoint({ lat: 15.376727, lng: 73.925272 })
lineString.pushPoint({ lat: 15.376747, lng: 73.925926 })
lineString.pushPoint({ lat: 15.377875, lng: 73.926001 })
lineString.pushPoint({ lat: 15.377916, lng: 73.925357 })
lineString.pushPoint({ lat: 15.376727, lng: 73.925272 })
var map = new H.Map(
document.getElementById('map'),
maptypes.vector.normal.map,
{
zoom: 15,
center: { lng: 73.925658, lat: 15.376116 }
});
var mapEvents = new H.mapevents.MapEvents(map);
var north = new H.map.Polygon(lineString)
var northgeo = north.getGeometry()
var northWKT = northgeo.toString()
console.log(northWKT)
map.addObject(north)
var zip = new JSZip()
zip.file("data.wkt", "NAME\tWKT\n" + "NorthFence\t" + northWKT)
zip.generateAsync({ type: "blob" }).then(content => {
saveAs(content, "hello.zip");
var formdata = new FormData()
formdata.append("zipfile", content)
axios.post("https://fleet.ls.hereapi.com/2/layers/upload.json", formdata,
{
headers: {
"content-type": "multipart/form-data"
},
parms: {
"layer_id": "15537",
"apikey": "apikeyhere"//here i use the rest api key of my freemium account
}
}).then((result) => {
console.log(result)
}, (err) => {
console.log("ERROR")
console.log(err)
})
}, (err) => {
console.log(err)
})
map.addEventListener('tap', function (evt) {
console.log(evt.type, evt.currentPointer.type);
})
but I'm getting the error
Error: Request failed with status code 401
at e.exports (spread.js:25)
at e.exports (spread.js:25)
at XMLHttpRequest.l.onreadystatechange (spread.js:25)
Is what I'm trying to do possible with a free account, it's not clear if it is. The video tutorial I'm following is out of date as there was a switch to using a API key instead of APP ID along with the API code.
To upload the WKT zip file via post request, I'm using the HERE Location Services REST APIs key and to draw the map I'm using HERE Maps API for JavaScript key
Yes you can create Geofence using freemium account. Here is the code with JS 3.1 you can try-
Index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body style="margin: 0">
<div id="map"></div>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://stuk.github.io/jszip/dist/jszip.js" type="text/javascript" charset="utf-8"></script>
<script src="heremap.js"></script>
<script>
const start = async () => {
const map = new HereMap("Your JS API KEY", document.getElementById("map"));
const lineString = new H.geo.LineString();
lineString.pushPoint({ lat: 37, lng: -121 });
lineString.pushPoint({ lat: 37.2, lng: -121.002 });
lineString.pushPoint({ lat: 37.2, lng: -121.2 });
lineString.pushPoint({ lat: 37, lng: -121 });
const polygon = new H.map.Polygon(lineString);
console.log(map.polygonToWKT(polygon));
map.draw(polygon);
const geofenceResponse = await map.uploadGeofence("1234", "Demo Layer", map.polygonToWKT(polygon));
};
start();
</script>
</body>
Heremap.js
class HereMap {
constructor(apikey, mapElement) {
//this.appId = appId;
//this.appCode = appCode;
this.apikey = apikey;
this.platform = new H.service.Platform({
'apikey': 'Your JS API Key'
});
this.map = new H.Map(
mapElement,
this.platform.createDefaultLayers().vector.normal.map,
{
zoom: 10,
center: { lat: 37, lng: -121 }
}
);
const mapEvent = new H.mapevents.MapEvents(this.map);
const behavior = new H.mapevents.Behavior(mapEvent);
this.geofencing = this.platform.getGeofencingService();
this.currentPosition = new H.map.Marker({ lat: 37.21, lng: -121.21 });
this.map.addObject(this.currentPosition);
this.map.addEventListener("tap", (ev) => {
var target = ev.target;
this.map.removeObject(this.currentPosition);
this.currentPosition = new H.map.Marker(this.map.screenToGeo(ev.currentPointer.viewportX, ev.currentPointer.viewportY));
this.map.addObject(this.currentPosition);
this.fenceRequest(["1234"], this.currentPosition.getGeometry()).then(result =>
{
if(result.geometries.length > 0) {
alert("You are in Geofence area")
} else {
console.log("you are out");
}
});
}, false);
}
draw(mapObject) {
this.map.addObject(mapObject);
}
polygonToWKT(polygon) {
const geometry = polygon.getGeometry();
return geometry.toString();
}
uploadGeofence(layerId, name, geometry) {
const zip = new JSZip();
zip.file("data.wkt", "NAME\tWKT\n" + name + "\t" + geometry);
return zip.generateAsync({ type:"blob" }).then(content => {
var formData = new FormData();
formData.append("zipfile", content);
return axios.post("https://fleet.ls.hereapi.com/2/layers/upload.json", formData, {
headers: {
"content-type": "multipart/form-data"
},
params: {
"apikey": 'Your JS API Key',
"layer_id": layerId
}
});
});
}
fenceRequest(layerIds, position) {
return new Promise((resolve, reject) => {
this.geofencing.request(
H.service.extension.geofencing.Service.EntryPoint.SEARCH_PROXIMITY,
{
"apikey": 'Your JS API KEY',
'layer_ids': layerIds,
'proximity': position.lat + "," + position.lng,
'key_attributes': ['NAME']
},
result => {
resolve(result);
}, error => {
reject(error);
}
);
});
}
}

Wordpress Plugin for Google Maps: How to return the Map

I have a PHP Site which takes Data from XML File to display Markers on a Google Maps. When I navigate direct to the page, everything is working. To integrate that code on my Wordpress Page, I thought about writing a plugin for that:
<? defined('ABSPATH') or die("Thanks for visting");
function showMap() { ?>
<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>
<div id="map"></div>
<script>
var customLabel = {
Location: {
label: 'L'
},
Brautaustatter: {
label: 'B'
},
Herrenausstatter: {
label: 'H'
},
Florist: {
label: 'F'
},
Konditor: {
label: 'K'
},
Sonstiges: {
label: 'S'
}
};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(48.2048, 16.375),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('showXML.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('location');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap">
</script>
<? add_shortcode( 'show_google_maps', 'showMap' ); ?>
<? } ?>
Now I do not know how to return the whole map with the markers? How can I solve this? Do I have to create a "main" function where all the other functions are nested? Is that what I want to achieve possible with that piece of code? Thanks for any advice!
BR,
Stefan

Google Maps API: Reference to markers using setDirections

With the Google Maps Javascript API, one can display markers and directions between them using DirectionsService and DirectionsRenderer (examples)
const directionsService = new google.maps.DirectionsService()
const directionsDisplay = new google.maps.DirectionsRenderer()
const mapOptions = {
zoom:7,
center: loc // some coordinates
}
const map = new google.maps.Map(document.getElementById('map'), mapOptions)
directionsDisplay.setMap(map)
const request = {
origin: start, // some coordinates
destination: end, // some coordinates
travelMode: 'DRIVING'
}
directionsService.route(request, function(result, status) {
if (status == 'OK') {
directionsDisplay.setDirections(result)
}
})
The above will show two markers (start, end) on the map with the highlighted route between them. What I need is a reference to each of the markers created (to set custom labels, register events, etc). Any way to do this while still using directionsDisplay.setDirections(result) or would I need to create everything manually?
You can't (easily/safely) get references to the markers. You can set the suppressMarkers option of the DirectionsRenderer, then create your own "custom" markers, from the data in the response.
directionsService.route(request, function(result, status) {
if (status == 'OK') {
directionsDisplay.setDirections(result);
createMarker(result.routes[0].legs[0].start_location, "A", "start marker", map, infowindow);
var lastLeg = result.routes[0].legs.length - 1;
createMarker(result.routes[0].legs[lastLeg].end_location, "B", "end marker", map, infowindow);
}
});
proof of concept fiddle
code snippet:
function initialize() {
const directionsService = new google.maps.DirectionsService();
const directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
var infowindow = new google.maps.InfoWindow();
const mapOptions = {
zoom: 7,
center: new google.maps.LatLng(37.4419, -122.1419) // some coordinates
}
const map = new google.maps.Map(document.getElementById('map'), mapOptions)
directionsDisplay.setMap(map)
const request = {
origin: {
lat: 37.4418834,
lng: -122.1430195
}, // some coordinates
destination: {
lat: 37.4529598,
lng: -122.1817252
}, // some coordinates
travelMode: 'DRIVING'
}
directionsService.route(request, function(result, status) {
if (status == 'OK') {
directionsDisplay.setDirections(result);
createMarker(result.routes[0].legs[0].start_location, "A", "start marker", map, infowindow);
var lastLeg = result.routes[0].legs.length - 1;
createMarker(result.routes[0].legs[lastLeg].end_location, "B", "end marker", map, infowindow);
}
})
}
google.maps.event.addDomListener(window, "load", initialize);
// Adds a marker to the map.
function createMarker(location, label, content, map, infowindow) {
var marker = new google.maps.Marker({
position: location,
label: label,
title: label,
map: map
});
marker.addListener('click', function(e) {
infowindow.setContent(content);
infowindow.open(map, this);
})
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

Raising an exception for a grey streetview location in Google Maps JavaScript API v3

Look, I'm using Google Maps JavaScript API v3. The user fills in an address and I show the streetview of that address. Everything's fine (a lot of locations work perfectly), till a enter a location like "Laken". It just displays grey, nothing else. I want to prevent the user from continuing to the next page with a grey image instead of a google maps streetview.
When I fill in Laken, the getPanoramaByLocation() function returns status == "OK", because it has found something, but its not a visible image, it's just grey. How can I prevent the API from doing this? Something like, when you can't display this location(is grey), display the next available location nearby.
Here's an extract from the code:
Function:
<script type="text/javascript">
//this is a standard location that I show when te user starts
var map;
var huis_lat,huis_lng;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333
});
//SAVE HOMELAT&LONGT
$('#geocoding_form').submit(function(e){
var address=document.getElementById("address").value;
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status)
{
if(status=='OK'){
var latlng = results[0].geometry.location;
huis_lat=latlng.lat();
huis_lng=latlng.lng();
verander(huis_lat, huis_lng);
document.getElementById("div_overlayStart").style.display="none";
document.getElementById("div_overlayThuis").style.display="block";
}
else if(!address) //no address
{
alert("fout?")
document.getElementById('alarm1').innerHTML = 'FILL IN ADDRESS';
}
else if(status=='UNKNOWN_ERROR')
{
document.getElementById('alarm1').innerHTML = 'UNKNOWN ERROR!';
}
else if(status=='ZERO_RESULTS')
{
document.getElementById('alarm1').innerHTML = 'UNKNOWN ADDRESS!';
}
}
});
});
});
</script>
HTML:
EX: Fill in: Kongingslaan 1, Laken
<body>
<form method="post" id="geocoding_form">
<div class="input">
<input type="text" id="address" name="address" />
<button type="submit" class="linksSocial" style="border: 0; background: transparent">
<img src="images/btn_job.png" width="231" heght="36" alt="submit" />
</button>
</div>
</form>
</body>
Function verander():
<script type="text/javascript">
function verander(google_lat, google_lng) {
var bryantPark = new google.maps.LatLng(google_lat, google_lng);
var panoramaOptions = {
position:bryantPark,
pov: {
heading: 185,
pitch:0,
zoom:1,
},
panControl : false,
streetViewControl : false,
mapTypeControl: false,
overviewMapControl: false ,
linksControl: false,
addressControl:false,
zoomControl : false,
}
map = new google.maps.StreetViewPanorama(document.getElementById("map_canvas"), panoramaOptions);
map.setVisible(true);
}
</script>
Use google.maps.StreetViewService.getPanoramaByLocation() to determine if there is a panorama available for the given location.
Quick and dirty solution. I noticed resizing the Window worked for me on this problem. And it also worked if you fire the event via js.
window.dispatchEvent(new Event('resize'));
Try this :
$(document).ready(function(){
var map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333
});
//SAVE HOMELAT&LONGT
$('#geocoding_form').submit(function(e) {
e.preventDefault();
var address = $('#address').val().trim();
if(!address.length) {
$('#alarm1').html('Fill in your address!');
}
GMaps.geocode({
address: address,
callback: function(results, status) {
if(status !== 'OK' || results.length == 0) {
$("#div_overlayStart").show();
$("#div_overlayThuis").hide();
}
if(status !== 'OK') {
$('#alarm1').text('Something went wrong!');
}
else if(results.length == 0) {
$('#alarm1').html('No results found!');
}
else {
$('#alarm1').text('');
var latlng = results[0].geometry.location;
verander(latlng.lat(), latlng.lng());
$("#div_overlayStart").hide();
$("#div_overlayThuis").show();
}
}
});
});
});
I also had problems with StreetView displaying 'grey' at some locations.
I don't like the solution given here.
Have a look at my solution in another post, which is also to do with StreetView being displayed 'grey' at some locations -->
Google maps streetview tiles do not load in Firefox initially, only after dragging
This solves the problem:
<script type="text/javascript">
var map;
var huis_lat,huis_lng;
var richting = 0;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333
});
//SAVE HOMELONG/LAT IN VAR
$('#geocoding_form').submit(function(e){
var address=document.getElementById("address").value;
/* STATUS
OK The request was successful.
UNKNOWN_ERROR The request could not be successfully processed, yet the exact reason for failure is unknown.
ZERO_RESULTS There are no nearby panoramas.
*/
//CHECK IF ADDRESS IS VALID (IS THEIR A VALID X/Y COORDINATE FOR IT?)
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status)
{
if(status=='OK'){
var latlng = results[richting].geometry.location;
huis_lat=latlng.lat();
huis_lng=latlng.lng();
verander(huis_lat, huis_lng);
document.getElementById("div_overlayStart").style.display="none";
document.getElementById("div_overlayThuis").style.display="block";
}
else if(!address) //no address
{
document.getElementById('alarm1').innerHTML = 'Gelieve u adres in te vullen!';
}
else if(status=='UNKNOWN_ERROR')
{
document.getElementById('alarm1').innerHTML = 'Er ging iets mis (onbekende fout)!';
}
else if(status=='ZERO_RESULTS')
{
document.getElementById('alarm1').innerHTML = 'Er is van deze locatie geen streetview beschikbaar!';
}
}
});
});
});
//+1 one for the array results[richting].geometry.location
function verhoog(){
var address=document.getElementById("address").value;
richting++;
//e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status)
{
if(status=='OK'){
var latlng = results[richting].geometry.location;
huis_lat=latlng.lat();
huis_lng=latlng.lng();
verander(huis_lat, huis_lng);
document.getElementById("div_overlayStart").style.display="none";
document.getElementById("div_overlayThuis").style.display="block";
}
}
});
}
</script>
Check if the panorama (streetview) for these X/Y coordinates is visible (not grey). I use the function getPanoramaByLocation to determine this. This returns a status like the previous one. If there are ZERO_RESULTS (=grey zone) it activates the function verhoog() that increments the array of results by 1.
<script type="text/javascript">
var map;
function verander(google_lat, google_lng) {
var bryantPark = new google.maps.LatLng(google_lat, google_lng);
//CHECK FOR GREY ZONE
var client = new google.maps.StreetViewService();
client.getPanoramaByLocation(bryantPark, 50, function(result, status) {
if (status == "ZERO_RESULTS") {
verhoog();
}
else if(status == "OK")
{
var panoramaOptions =
{
position:bryantPark,
pov: {
heading: 185,
pitch:0,
zoom:1,
},
panControl : false,
streetViewControl : false,
mapTypeControl: false,
overviewMapControl: false ,
linksControl: false,
addressControl:false,
zoomControl : false,
}
map = new google.maps.StreetViewPanorama(document.getElementById("map_canvas"), panoramaOptions);
map.setVisible(true);
}
else if(status=='UNKNOWN_ERROR')
{
alert("Er ging iets mis");
}
});
}
</script>

Initializing Google Maps as an AMD module

To initialize google.maps as an AMD module, compliant with twitter/flight and requirejs, use:
define([
'components/flight/lib/component',
'async!http://maps.google.com/maps/api/js?key=AIzaSyDp9D9Db1CWfeGUJ1bin45s2WKZN5sapuM&sensor=false'
], function(defineComponent){
return defineComponent(newMap);
function newMap () {
this.defaultAttrs({
// Selector
mapDiv: '#map',
// Map Canvas
mapCanvas: {},
// Initialized?
initializedMap: false
});
this.initializeMap = function () {
var mapCenter = new google.maps.LatLng(39.960664,-75.605488);
var mapOptions = {
zoom: 15,
center: mapCenter,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
this.attr.mapCanvas = new google.maps.Map(document.getElementById("map"), mapOptions);
if (this.attr.mapCanvas != {} ) {
this.attr.initializedMap = true;
this.trigger(document, 'mapInitialized', {
status: this.attr.initializedMap
});
};
// ### Map events
//-----------
// Mouse Up
google.maps.event.addListener(this.attr.mapCanvas, 'mouseup', function() {
this.trigger('mouseup');
});
// Zoom Changed
google.maps.event.addListener(this.attr.mapCanvas, 'zoom_changed', function() {
this.trigger('zoomChanged');
});
};
this.mouseup = function () {
console.log("what");
}
this.zoomChanged = function () {
console.log("is up");
}
this.after('initialize', function () {
this.on('mouseup', this.mouseup);
this.on('zoomChanged', this.zoomChanged);
this.on('initializeMap', this.initializeMap);
this.trigger('initializeMap');
});
}
});
I put together a Google Maps AMD loader plugin, which adds some functionality on top of the async! loader.
require.config({
googlemaps: {
params: {
key: 'abcd1234', // sets api key
libraries: 'geometry' // set google libraries
}
}
});
require(['googlemaps!'], function(gmaps) {
// google.maps available as gmaps
var map = new gmaps.Map('map-canvas');
});

Resources