Google Maps API - Get New Center Coordinates after map is moved - google-maps

I'm using the Google Maps API to display a map, but I now need to capture the centre coordinators if the user moves the map. I'm after the new lat/long of the new centre of the map after it has been moved.
Looking at the Maps Events docs I can see a few options here:
center_changed
dragend
that I could potentially move. I've tried both but can't get the syntax right and not sure how to retrieve the centre lat/long. Here's my latest attempt
google.maps.event.addListener(map, 'dragend', function() {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log("current latitude is: "+latitude);
console.log("current longitude is: "+longitude);
});
but I get an error TypeError: undefined is not an object (evaluating 'event.latLng.lat') when this runs.
Can anyone tell me what the most approrpriate event to use here and how I can get the new centre co-ordinatates when the map has changed by the user dragging it.

If you want the center values when it changes, use the 'center_changed' event:
center_changed
Arguments: None
This event is fired when the map center property changes.
google.maps.event.addListener(map, "center_changed", function() {
var center = this.getCenter();
var latitude = center.lat();
var longitude = center.lng();
console.log("current latitude is: " + latitude);
console.log("current longitude is: " + longitude);
});
proof of concept fiddle
code snippet:
function initMap() {
var myLatlng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatlng
});
google.maps.event.addListener(map, "center_changed", function() {
var center = this.getCenter();
var latitude = center.lat();
var longitude = center.lng();
console.log("current latitude is: " + latitude);
console.log("current longitude is: " + longitude);
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Related

Algolia and google filter results based on user position

Hi I am using Google maps alongside algolia where I have an index 'locations' with 'lat' and 'lng'.
I am getting user location and watching position, I am also displaying markers from database based on lng and lat however I want to add a bit to it:
So I have followed that link:
https://www.algolia.com/doc/guides/geo-search/geo-search-overview/
And came up with:
#extends('master') #section('title', 'Live Oldham')
#section('extrafiles')
<script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50&language=en"></script>
<script type="text/javascript" src="{!! asset('js/homesearch.js') !!}"></script>
#endsection
#section('content')
<div id="map_canvas" style="height:600px;"></div>
#endsection
and js:
$(document).ready(function() {
var map;
function initializeMap(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(position) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
));
}
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition(position);
console.log(position);
}
function watchCurrentPosition(position) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position,
)
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}else{
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 100 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
var markers = [];
//alert("heelo");
var fitMapToMarkersAutomatically = true;
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
console.log(hit)
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
markers.push(marker);
}
// Automatically fit the map zoom and position to see the markers
if (fitMapToMarkersAutomatically) {
var mapBounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
mapBounds.extend(markers[i].getPosition());
}
map.fitBounds(mapBounds);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
algoliaHelper.setQueryParameter('aroundRadius', 5000).search(); // 5km Radius
});
However there are few problems with this that I don't know how to tackle:
When user is moving, it doesn't center the map on the marker.
At this moment marker jumps between location when user moves, I would like for the marker to dynamically move on the map when user moves.
I want to use algolia to dynamically set markers, so I want to show markers with 5km radius from user location, and dynamically add or remove markers that are outside it.
I can't help you much with those questions since it's mostly about how to use GMap JS lib and I'm not experienced with it. However, something else catched my eyes:
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
You should put your coordinates in the _geoloc field in order to be able to use the geo-search features. It looks like this:
_geoloc: {
lat: 40.639751,
lng: -73.778925
}

How to remove all events from a KML layer in Google Maps API V3

I'm making a web application that uses google maps to help with solar deployment. In essence, I'm loading a google map in full screen and overlaying KML layers using this code:
window.solarLayer = new google.maps.KmlLayer({
url: 'somelink'
});
window.solarLayer.setMap(window.map);
Another feature of this application is that a user is able to click anywhere in the map, and using the latitude and logitude at the click point, it would return solar data to the user.
This all works fine by using a click event handler as such:
google.maps.event.addListener(map, 'click', function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
});
However, the portion of the map that has the KML layer only registers clicks for the layer and does not access the click event I created...
Does anyone know how to disable click events for KML layers? or how to make my event listener supersede that of the KML layer?
I have tried getting the lat and long by using a click event on the KML layer as well as the map but that only yields a static lat long of where that layer is positioned, not where the user actually clicks.
Thanks for any help in advance!
Set the clickable option of the KmlLayer to false.
from the KmlLayerOptions documentation:
clickable| Type: boolean
If true, the layer receives mouse events. Default value is true.
code snippet:
var map;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
window.solarLayer = new google.maps.KmlLayer({
url: 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml',
clickable: false
});
window.solarLayer.setMap(window.map);
google.maps.event.addListener(map, 'click', function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
document.getElementById('coords').innerHTML = event.latLng.toUrlValue(6);
console.log(latitude + ', ' + longitude);
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="coords"></div>
<div id="map_canvas"></div>

Google Maps V3 InfoWindow ignores latLng position

My map has no markers. In response to a click on the map, it pops up an infowindow with Lat/long shown in decimal to 5 dp and in Degrees minutes seconds. An open window is always closed prior to responding to a new click. The position is specified by position: latLng, but the infowindow is ALWAYS at the top left. I've spent days on this, and I feel I'm missing something. Code snippet below. Any ideas?
google.maps.event.addListener(map, 'click', function (event) {
var lat = event.latLng.lat(),
lng = event.latLng.lng(),
latLng = event.latLng,
strHtml;
//
// strHtml build code omitted but succesfully uses lat and lng to produce
// e.g. Latitude : 51.72229 N (51° 43' 20'' N)
// Longitude : 1.45827 E (1° 27' 30'' E)
//
// If an infowindow is open, then close it
if (openedInfoWindow != null) openedInfoWindow.close();
// latLng monitored to check it is there before use in infowindow
alert(latLng); // returns correct values which position then ignores!
var infoWindow = new google.maps.InfoWindow({
position: latLng,
content: strHtml,
maxWidth: 420
});
// Open infoWindow
infoWindow.open(map,this);
// Remember the opened window
openedInfoWindow = infoWindow;
// Close it if X box clicked
google.maps.event.addListener(infoWindow, 'closeclick', function() {
openedInfoWindow = null;
});
});
You have several problems with this code. The second parameter of the infowindow's open method has to be an MVCObject in the Core API only the Marker class can be used as an anchor. You should not need to set the infowindow variable to null and create a new infowindow object each time. You only need a single infowindow and then change its content and position. This way there is only one infowindow shown at a time.
Here is a fiddle of a working example: http://jsfiddle.net/bryan_weaver/z3Cdg/
relevant code:
google.maps.event.addListener(map, 'click', function (evt) {
var content = "<div class='infowindow'>";
content += "Latitude: " + evt.latLng.lat() + "<br/>";
content += "Longitude: " + evt.latLng.lng() + "</div>";
HandleInfoWindow(evt.latLng, content);
});
function HandleInfoWindow(latLng, content) {
infoWindow.setContent(content);
infoWindow.setPosition(latLng);
infoWindow.open(map);
}
The 2nd (optional)argument of infoWindow.open() is expected to be an MVCObject that exposes a position-property.
the this argument in the callback refers to a google.maps.Map-Instance(map), which is an MVCObject, but doesn't have a position-property.
Remove the 2nd argument from infoWindow.open(map,this); .

Google Map - Convert v2 to v3 -drag icon and retrieve lat/long

I have an application that I wrote years ago in Google Map v2 that displayed a map from a given initial lat/long and placed an icon on the map. This webpage was a form with a text box for the lat and long. The page allowed the user to drag the icon to actual location of where a wildfire was located. The new lat/long was placed into the text box and the user could submit the form. I have not found a suitable replacement in v3 for this process. And now I get an error message that a new API key is required from Google Maps. But I also know that in May that v2 may no longer work. So I would like to update this app to v3. Any ideas of where I can find this? Here is an example of the old page http://nfsdata.unl.edu/wildfire/testmap.asp The page is writen in ASP. And we do not have access to PHP on this server. Thanks
That is a very straightforward application.
Your v2 code:
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
var center = new GLatLng(41.33,-96.95);
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(center, 13);
var marker = new GMarker(center, {draggable: false});
map.addOverlay(marker);
GEvent.addListener(map, "click", function(overlay, point) {
if (overlay) {
map.removeOverlay(overlay);
} else {
map.clearOverlays()
map.addOverlay(new GMarker(point));
document.getElementById("loclats").value = point.lat();
document.getElementById("loclongs").value = point.lng();
}
});
}
}
//]]>
</script>
Simple translation to v3 (not tested):
<script type="text/javascript">
//<![CDATA[
function load() {
var center = new google.maps.LatLng(41.33,-96.95);
map = new google.maps.Map(document.getElementById("map"),{
center:center,
zoom: 13
});
var marker = new google.maps.Marker({
map: map,
position:center
});
google.maps.event.addListener(marker, "click", function() {
marker.setMap(null);
});
google.maps.event.addListener(map, "click", function(evt) {
var point = evt.latLng;
marker.setPosition(point);
document.getElementById("loclats").value = point.lat();
document.getElementById("loclongs").value = point.lng();
});
}
}
//]]>
</script>
working example

Add user location marker to existing gmap

I am using Drupal 7 - Location, GMap module. I have a view that renders the result in a gmap. Everything works fine here and I get all the markers. Now I need a Find My location button which shows the users current location and adds a marker to the existing map.
Google Map Api V3 always works on a newly created map and I couldn't find a function which returns an existing map in the current page.
Gmap module provides a JS function - Drupal.gmap.getMap('ur-map-id') which is supposed to return a pointer to the map whose id is given. But this did not work.
Could someone please guide me as to how I should go about this? Can I get it work with Google Maps API? I need to retain the original map with all its markers.
Here's something for reference.
if (typeof(navigator.geolocation) !== 'undefined') {
var showUserOnMap = function(position) {
var map = Drupal.gmap.getMap('gmap-auto1map-gmap0');
if (typeof(map) !== 'undefined' && map !== false) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
var marker = {
latitude: latitude,
longitude: longitude,
markername: Drupal.t('You'),
opts: {
title: Drupal.t('You')
}
}
marker.opts.position = new google.maps.LatLng(latitude, longitude);
marker.opts.map = map.map;
Drupal.gmap.factory.marker(marker.opts);
}
};
// Get the current location
navigator.geolocation.getCurrentPosition(showUserOnMap);
}
I am having this issue as well, you can put this jquery code in for it to actually centre around your current location - but no marker is added. Just add it anywhere in your theme,
jQuery(document).ready(function() {
jQuery(function($) {
$.extend({
initialize: function () {
var m = Drupal.gmap.getMap('auto1map');
if (m.map && m.markersready) {
$.setCoords();
}
else {
m.bind('markersready', function(data) {
$.setCoords();
});
}
},
setCoords: function () {
navigator.geolocation.getCurrentPosition(function (position) {
var gmap = Drupal.gmap.getMap('auto1map').map;
var lat = position.coords.latitude;
var lng = position.coords.longitude;
gmap.setCenter(new google.maps.LatLng(lat, lng));
gmap.setZoom(13);
});
}
});
$.initialize();
});
});
Now you can centre your map around your location and now I need to figure out a way to place a marker down at this location.