I need some help with Google maps.
I am not able to reduce the zoom level in google maps after fitbound.
The problem is that I am getting a very highly zoomed google map. I have tried setting the zoom level to 5 (as you can see in the codes) but this has no effect to the very highly zoomed map.
I want to achieve this
But right now its coming like this : http://redstoneinfotech.com/OSAcontact/
Here is the map.js
window.map = {
map_type: 'ROADMAP',
map_zoom: 5,
map_style: 'blackwhite',
map_scrollable: 'on',
marker: 'show',
label: ['Castle Hill', 'Sydney', 'Melbourne', 'Milton', 'Brooklyn Park', 'Wangara '],
address: '',
latlng: ['-33.7301484, 150.9626532', '-33.8473567, 150.6517813',
'-37.970154, 144.4926753 ', ' - 27.4691402, 152.9962768 ',
' - 34.9303517, 138.5346949 ', ' - 31.7928896, 115.8157212 '
],
center_latlng: '',
markerURL: 'assets/images/marker.png',
auto_center: true,
};
'use strict';
jQuery(document).ready(function($) {
$('.google-map').each(function() {
var mapDiv = $(this);
var mapData = window[mapDiv.attr('id')];
function createMap() {
var style = [{
'stylers': [{
'saturation': -100
}]
}];
var options = {
zoom: parseInt(mapData.map_zoom, 5),
scrollwheel: false,
draggable: mapData.map_scrollable === 'on',
mapTypeId: google.maps.MapTypeId[mapData.map_type]
};
if (mapData.map_style === 'blackwhite') {
options.styles = style;
}
return new google.maps.Map(mapDiv[0], options);
}
// create map
var map = createMap();
// create bounds in case we dont have center map coordinates
// every time a marker is added we increase the bounds
var bounds = new google.maps.LatLngBounds();
function addMarker(position, index) {
if (mapData.marker === 'show') {
var image = {
url: mapData.markerURL,
size: new google.maps.Size(30, 48),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(10, 40)
};
var marker = new google.maps.Marker({
position: position,
icon: image,
map: map
});
// extend bounds to encase new marker
bounds.extend(position);
// add label popup to marker
if (mapData.label[index] !== undefined) {
var infoWindow = new google.maps.InfoWindow({
content: mapData.label[index]
});
google.maps.event.addListener(marker, 'click', function(e) {
infoWindow.open(map, this);
});
}
}
}
// centre map
var centerMapWithCoordinates = !mapData.auto_center;
if (centerMapWithCoordinates) {
if (mapData.center_latlng !== undefined) {
var center_lat_lng = mapData.center_latlng.split(',');
var center_map = new google.maps.LatLng(center_lat_lng[0], center_lat_lng[1]);
map.setCenter(center_map);
} else {
console.log('You have not set any coordinates for the map to be centered at.');
}
}
// create markers
if (mapData.address) {
// lookup addresses
var markerAddressCount = 0;
$.each(mapData.address, function(index, address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (undefined !== results[0]) {
var location = results[0].geometry.location;
var position = new google.maps.LatLng(location.lat(), location.lng());
addMarker(position, index);
}
// increment count so we can keep track of all markers loaded
markerAddressCount++;
// if all markers are loaded then fit map
if (!centerMapWithCoordinates && markerAddressCount === mapData.address.length) {
map.fitBounds(bounds);
}
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
});
} else if (undefined !== mapData.latlng) {
for (var i = 0; i < mapData.latlng.length; i++) {
var coordinates = mapData.latlng[i].split(',');
var position = new google.maps.LatLng(coordinates[0], coordinates[1]);
addMarker(position, i);
}
if (!centerMapWithCoordinates) {
map.fitBounds(bounds);
}
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(5);
google.maps.event.removeListener(boundsListener);
});
});
});
I have tried with many options but none of them is working. Please help.
As much as I can see, the problem is with the Google Maps sdk. Why? because they are calling to bounds_changed callback before the fitBounds is actually ended.
That's why it causes the zoom not to work because they didn't finish to zoom it as part as the bounds changing in fitBounds.
So the solution is to put the setZoom in setTimeout. In this way, this code will run only after the execution of the current process - fitBounds.
setTimeout(() => {
this.setZoom(5);
}, 0);
It works for me. Let me know if it works for you.
Related
Hello fellow Stackoverflow members.
I have offered to help out our local communities emergency volunteer group with an improved alert map for notifying members of incidents close by to our town.
I have been using the google maps api, along with the google places api.
I have managed to bring in their news alert JSON data, match it with their custom icons, and display it on the map successfully. However I am now struggling to get the places searchBox to update the map based on the address users are entering into the search.
NB: The search is auto-completing fine, but the map is not updating. Current error is "map.fitBounds is not a function"
My reference link which I have been using to try and get the places search integrated: https://github.com/googlemaps/js-samples/blob/737eb41e78f9cad28e2664b68450676e91424219/dist/samples/places-searchbox/inline.html
I have attached my code below. With a comment where I have added the latest edits to the code for the search function. A fresh perspective would be greatly appreciated.
UPDATE: I have compiled a JSFiddle for easier handling:
https://jsfiddle.net/mcmacca002/zvghd0nu/
Thank you and appreciated.
// BUILD GOOGLE MAPS:
var GoogleMap = {
map: null,
markers: {},
init: function(lat, lng, places) {
var self = this;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(lat, lng)
};
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(50, 50)
});
// SEARCH STARTS HERE (ALONG WITH ISSUES):
var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
// END OF SEARCH HERE.
$.each(places, function() {
self.addMarker(this);
});
this.setCenterPoint();
},
// Create map markers
addMarker: function(place) {
var self = this;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(place.coordinate.latitude, place.coordinate.longitude),
map: self.map,
title: place.name,
icon: place.image
});
console.log(place);
// Create information event for each marker
marker.info_window_content = 'TEST'
self.markers[place.id] = marker
google.maps.event.addListener(marker, 'click', function() {
self.infowindow.setContent(marker.info_window_content)
self.infowindow.open(self.map, marker);
});
},
// Update map markers
updateMarkers: function(records) {
var self = this;
$.each(self.markers, function() {
this.setMap(null);
})
$.each(records, function() {
self.markers[this.id].setMap(self.map);
});
//Set map center
if (records.length) self.setCenterPoint();
},
// Set centre point for map
setCenterPoint: function() {
var lat = 0,
lng = 0;
count = 0;
//Calculate approximate center point based on number of JSON entries
for (id in this.markers) {
var m = this.markers[id];
if (m.map) {
lat += m.getPosition().lat();
lng += m.getPosition().lng();
count++;
}
}
if (count > 0) {
this.map.setCenter(new google.maps.LatLng(lat / count, lng / count));
}
}
};
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div class="container" id="map" style="height:900px;"></div>
You have an error, because you have a wrong reference to this. I updated your Jsfiddle here: https://jsfiddle.net/k23auboq/ but I will also show you what went wrong down below.
init: function(lat, lng, places) {
// ...
var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
google.maps.event.addListener(searchBox, 'places_changed', () => { // if you pass an arrow function here instead, 'this' will be taken from the outer context
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}
this.map.fitBounds(bounds); // this.map.fitBounds(...) now exists and works
searchBox.set('map', map);
this.map.setZoom(Math.min(map.getZoom(), 12));
});
// ...
},
To simplify it a bit take a look at the following examples:
function Test() {
this.map = 'test map';
this.callbackAction = function (callback) {
callback();
}
this.action = function () {
this.callbackAction(function () { // callback passed as 'function'
console.log(this.map);
});
}
return this;
}
const instance = new Test();
instance.action();
vs
function Test() {
this.map = 'test map';
this.callbackAction = function (callback) {
callback();
}
this.action = function () {
this.callbackAction(() => { // callback passed as 'ARROW function'
console.log(this.map);
});
}
return this;
}
const instance = new Test();
instance.action();
I have updated the answer which was provided above. The answer was technically correct, however using the bounds method will zoom the map down to level 1.
Here is a solution which should work for you. I have not been able to add a pin to the searched location. Hopefully somebody else may be able to help you there as I have only applied what I have learned using leaflet.js which is slightly different to Google maps, and am only still learning Javascript.
var GoogleMap = {
map: null,
markers: {},
init: function(lat, lng, places) {
var self = this;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(lat, lng),
draggable: true
};
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(10, 10)
});
// SEARCH STARTS HERE:
var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
google.maps.event.addListener(searchBox, 'places_changed', () => {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
var marker = new google.maps.Marker({
title: places.name,
zoom: 4,
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
bounds.extend(place.geometry.location);
});
marker.setPosition(place.geometry.location);
}
// ADDING PANTO FOR RETAINING THE MAP ZOOM LEVEL - INSTEAD OF SETZOOM :D
this.map.panTo(marker.getPosition());
});
// WHICH THEN ENABLES YOU TO REMOVE THIS:
// this.map.fitBounds(bounds);
// searchBox.set('map', map);
// this.map.setZoom(Math.min(map.getZoom(), 12));
// END OF SEARCH HERE.
when map bound moved by user, make disappear old position markers and display new markers.
For an example you can check this map. Markers are moving every time bounds updated and clearing the old position markers. I am exactly trying to do this.
UPDATED 2
what I have done so far is right below. No errors but, still seeing all markers at once..?
data(){
return {
bounds:{},
map: {},
mapName: "map",
estates: [],
}
},
mounted() {
axios.get('/ajax').then((response) => {
this.estates = response.data
this.insertMarkers();
});
this.initMap();
},
methods: {
initMap: function() {
this.bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(34.652500, 135.506302),
);
var mapOptions = {
mapTypeId: 'roadmap',
center: new google.maps.LatLng(0, 0),
zoom: 8
};
let self = this;
this.map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
var boundsListener = google.maps.event.addListener((this.map), 'bounds_changed', function(event) {
self.getMarkers();
});
this.map.fitBounds(this.bounds);
},
getMarkers: function() {
let bounds = this.map.getBounds();
let southWest = bounds.getSouthWest();
let northEast = bounds.getNorthEast();
console.log(southWest);
axios.get('/ajax', {
params: {
fromLat: southWest.lat()-0.01,
toLat: northEast.lat()-0.01,
fromLng: southWest.lng()+0.01,
toLng: northEast.lng()+0.01,
}
}).then((response) => {
this.estates = response.data;
this.updateMarkers();
});
},
updateMarkers: function() {
google.maps.event.addListener(map, 'idle', function() {
var map = this.map;
var estates = this.estates;
let i = 0;
for (i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
this.markers = [];
for (i = 0; i < estates.length; i++) {
var position = new google.maps.LatLng(estates[i].lat, estates[i].lng);
var marker = new google.maps.Marker({
position: position,
map: map,
label: {
text:
estates[i].price.toString().length == 1 ?
estates[i].price.toString().replace("1", "未定") :
estates[i].price.toString() + "万",
color: '#fff',
},
icon: '/img/marker.png',
url: "/pages/" + estates[i].id,
});
this.markers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
}
});
},
As I said in my comment, you can do it the other way around. Fetch only markers that are visible within the map viewport. You just need to reorganize your code a bit and modify your database query.
You need to pass a minimum and maximum latitude and longitude to your controller so that you can query the DB for markers between the given latitudes and longitudes. You can get these by getting your map bounds and extracting southwest and northeast lat/lng.
export default {
data() {
return {
bounds: {},
map: {},
mapName: "map",
estates: [],
markers: [] // Added markers array here
}
},
mounted() {
this.initMap(); // On "mounted" only call initMap
},
methods: {
initMap: function() {
//giving specific location of japan.
this.bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(34.652500, 135.506302),
);
var mapOptions = {
mapTypeId: 'roadmap',
center: new google.maps.LatLng(0, 0),
zoom: 5
};
this.map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
let self = this;
var boundsListener = google.maps.event.addListener((this.map), 'idle', function(event) {
self.getMarkers(); // When map is idle, get markers
});
this.map.fitBounds(this.bounds);
},
getMarkers: function() {
// Get current map bounds
let bounds = this.map.getBounds();
let southWest = bounds.getSouthWest();
let northEast = bounds.getNorthEast();
// Send request with min/max latitude and longitude to only fetch markers for that area
axios.get('/ajax', {
params: {
fromLat: southWest.lat(),
toLat: northEast.lat(),
fromLng: southWest.lng(),
toLng: northEast.lng(),
}
}).then((response) => {
this.estates = response.data;
this.updateMarkers();
});
},
updateMarkers: function() {
// Remove previous markers
for (let i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
// Reset markers array
this.markers = [];
// Add current markers
for (i = 0; i < estates.length; i++) {
var position = new google.maps.LatLng(estates[i].lat, estates[i].lng);
var marker = new google.maps.Marker({
position: position,
map: map,
icon: '/img/marker.png',
url: "/pages/" + estates[i].id,
});
// Push marker to markers array for future removal
this.markers.push(marker);
}
}
}
}
In your controller, you need to get the parameters you send with the axios request (fromLat, toLat, etc.)
public function ajax() {
// Here you need to retrieve the parameters sent by the axios request !
// And set them as $fromLat, $toLat, etc.
$data = \DB::table('allestates')
->where('lat', '>', $fromLat)
->where('lat', '<', $toLat)
->where('lng', '>', $fromLng)
->where('lng', '<', $toLng)
->get();
$response = response()->json($data);
return $response;
}
Untested, but that should work. You need to adapt some parts! Read my comments in the code as well.
Note: the bounds_changed event is triggered repeatedly when a user drags the map, so this way you are going to send a lot of requests to your database. Instead, you should probably prefer another event such as idle or delay the trigger of your ajax call somehow to reduce the number of queries.
You need to store old Value and compare with new one you need timeout function to update each time iterval ex window.setTimeout(insertMarkers,3000)
for(var i=0, len=res.length; i<len; i++) {
//Do we have this marker already?
if(markerStore.hasOwnProperty(res[i].driver_id)) {
markerStore[res[i].id].setPosition(new google.maps.LatLng({lat: parseFloat(res[i].lat), lng: parseFloat(res[i].lng)}));
} else {
marker = new google.maps.Marker({
position: {lat: parseFloat(res[i].lat), lng: parseFloat(res[i].lng)},
map:map
});
google.maps.event.addListener(marker, 'click', (function(marker, i,id) {
return function() {
console.log(id)
}
})(marker, i,id));
markerStore[res[i].id] = marker;
}
}
markerStore[estate.id] = marker;
}
});
UPDATE
mounted() {
.
.
.
this.initMap();
window.setTimeout(this.insertMarkers,3000)
},
methods: {
.
.
.
insertMarkers: function() {
var marker=[];
var markerStore = {};
this.estates.forEach((estate, index) => {
//Do we have this marker already?
if(markerStore.hasOwnProperty(estate.id)) {
markerStore[estate.id].setPosition(new google.maps.LatLng({lat: parseFloat(estate.lat), lng: parseFloat(estate.lng)}));
} else {
marker = new google.maps.Marker({
icon: '/img/marker.png',
position: {lat: parseFloat(estate.lat), lng: parseFloat(estate.lng)},
map:map
});
var es_id=estate.id;
google.maps.event.addListener(marker, 'click', (function(marker, index,es_id) {
return function() {
console.log(es_id)
window.location.href = "/pages/" + es_id;
}
})(marker, index,es_id));
markerStore[estate.id] = marker;
}
});
I am using the following scripting to load homes for sale on to my Google Map. I like to know if this is possible and if it is -- I need help from a really good Google Map programmer to help add it.
What I Am Look For
If one of the addresses within the left panel cannot be found by Google or is out of boundaries, it still loads the element and address to the left panel -- but in a disabled state by adding a class to that element. Can this be done?
Mapping Boundaries
Here is the boundaries, if the marker is within this area it adds the marker else disables the element. If the with boundaries cannot be done, I will take the option of Google not finding it.
http://www.freemaptools.com/radius-around-point.htm?clat=44.512176171071054&clng=-81.08184814453125&r=96.39586143951128&lc=FFFFFF&lw=1&fc=00FF00
Scripting I Am Using
http://www.raymondcamden.com/demos/2012/dec/1/new4.html
Here Is What I Have So Far
I put together the follow scripting based on the site above, just looking to add the missing location element to this concept.
var map;
var markers = [];
var lastinfowindow;
var locIndex;
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fn, scope) {
for (var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
var data = [
{address:'123 GODERICH ST GODERICH ONTARIO',title:'123 GODERICH ST'},
{address:'123 KNOWLES LANE KINCARDINE ONTARIO',title:'123 KNOWLES LANE'}
];
function Initialize() {
var latlng = new google.maps.LatLng(44.00, -80.00);
var mapOptions = {
zoom : 8,
center : latlng,
mapTypeId : google.maps.MapTypeId.ROADMAP,
scaleControl : true,
mapTypeControl : false,
navigationControlOptions : {
style : google.maps.NavigationControlStyle.SMALL
},
scrollwheel : false,
minZoom : 7,
maxZoom : 15,
keyboardShortcuts : false,
disableDoubleClickZoom : true,
draggable : true,
backgroundColor : '#FFFFFF'
};
var mapStyles = [{
featureType: 'poi',
stylers: [{
visibility: 'off'
}]
}];
var styledMap = new google.maps.StyledMapType(mapStyles, {name: 'Styled Map'});
map = new google.maps.Map(document.getElementById('map'), mapOptions);
geocoder = new google.maps.Geocoder();
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
icon = new google.maps.MarkerImage('/pointer.png', new google.maps.Size(19, 29), new google.maps.Point(0, 0), new google.maps.Point(8, 29));
data.forEach(function(mapData,idx) {
geocoder.geocode({'address':mapData.address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: mapData.title,
icon: icon
});
var contentHtml = "<div style='width:300px;height:200px'><h3>"+mapData.title+"</h3>"+mapData.address+"</div>";
var infowindow = new google.maps.InfoWindow({
content: contentHtml
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
marker.locid = idx+1;
marker.infowindow = infowindow;
markers[markers.length] = marker;
var sideHtml = '<p class="loc" data-locid="'+marker.locid+'"><b>'+mapData.title+'</b><br/>';
sideHtml += mapData.address + '</p>';
$('#locations').append(sideHtml);
}
});
});
}
window.onload = Initialize;
I am currently in the process of seeing if I can do this and will update along the way. Thanks!!
You need to check if the status of the geocode call is either
ZERO_RESULTS
INVALID_REQUEST
or one of the other status codes in the Maps API, such as
geocoder.geocode({'address':mapData.address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
//handle valid address search
} else if (status === google.maps.GeocoderStatus.INVALID_REQUEST
|| status === google.maps.GeocoderStatus.ZERO_RESULTS) {
//handle no results returned
}
}
If you have a geocode request return one of those statuses, you can add the element to the map, but set the marker to a reduced visibility state or some other option that you prefer. For something like this, look into the MarkerOptions and associated Marker documentation at the link above.
I've created a script that places a marker on a map based on the area you click your mouse over. Once that marker is placed, when your mouse hovers over the marker, an infobox should appear with the address of where the marker is placed. However, the infobox isn't showing up because when I call "info_text", it returns undefined. I realized that I needed to add in a callback function but I don't think I'm implementing it correctly. Could anyone help me fix my code? Thanks
My code:
var geocoder;
function initialize()
{
geocoder = new google.maps.Geocoder();
var event = google.maps.event.addListener;
// intializing and creating the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
event(map,'click',function(e){
var marker = placeMarker_and_attachMessage(e.latLng,map,count);
count = count + 1;
});
} // end of initalize.
function placeMarker_and_attachMessage(position,map)
{
var event = google.maps.event.addListener;
var message = ['This', 'is', 'the', 'secret', 'message'];
var marker = new google.maps.Marker({
position: position,
map: map
});
var pos = info_text(position);
alert('pos is: ' + pos);
var infowindow = new google.maps.InfoWindow({
content: 'hello'
});
event(marker,'mouseover',function(){
infowindow.open(map,this);
});
event(marker,'mouseout',function(){
infowindow.close();
});
} // end of function.
function info_text(position)
{
var lat = parseFloat(position.lat());
var lng = parseFloat(position.lng());
alert('lat,lng is: ' + (lat,lng));
var latlng = new google.maps.LatLng(lat,lng);
alert('just before geocode');
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
alert('in info_text If statement');
if(results[1])
{
alert('in inner if statement');
var finalResult = myCallback(results[1].formatted_address);
return finalResult;
}
else
{
alert('no results found');
}
}
else
{
alert('could not pinpoint location');
}
});
}
function myCallback(loc)
{
alert('i have a location!');
return loc;
}
google.maps.event.addDomListener(window, 'load', initialize);
Your function info_text doesn't return anything, so this line:
var pos = info_text(position);
is where pos is undefined.
You need to include:
return something;
at some point in your function (like you have done further down).
Added
Your function myCallback returns a value, but where it is used:
myCallback(results[1].formatted_address);
it doesn't store the return-value anywhere - it is just discarded.
Does any of you know how to add a marker on you currentPosition in google maps using sencha?
This is my code:
var map;
var defaultLocation;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var spots;
var infowindow = new google.maps.InfoWindow();
owt.views.RoutePanel = Ext.extend(Ext.Panel, {
title: 'route',
fullscreen:true,
layout: 'card',
items: [
map = new Ext.Map({
useCurrentLocation: true,
mapOptions: {zoom:10},
listeners: {
delay: 500,
afterrender: function() {
var geo = new Ext.util.GeoLocation({
accuracy: 1,
autoUpdate: true,
listeners: {
locationupdate: function (geo) {
center = new google.maps.LatLng(geo.latitude, geo.longitude);
zoom = 10;
if (map.rendered){
map.update(center)
}
else{
map.on('activate', map.onUpdate, map, {single: true, data: center});}
},
locationerror: function (geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {
if (bTimeout) {
alert('Timeout occurred.');
}
else {
alert('Error occurred.');
}
}
}
});
geo.updateLocation();
spots = [];
for (var i in owt.stores.spotStore.data.map) {
spots.push(new google.maps.LatLng(owt.stores.spotStore.data.map[i].data.lat,
owt.stores.spotStore.data.map[i].data.lng))
switch (owt.stores.spotStore.data.map[i].data.categorie_id) {
case 1:
var image = 'assets/images/monumenten_icon.png';
break;
case 2:
var image = 'assets/images/horeca_icon.png';
break;
case 3:
var image = 'assets/images/toilet_icon.png';
break;
case 4:
var image = 'assets/images/shopping_icon.png';
break;
}
var markers = [];
var spotMarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(owt.stores.spotStore.data.map[i].data.lat,owt.stores.spotStore.data.map[i].data.lng),
map: this.map,
icon: image
});
google.maps.event.addListener(spotMarker, 'dblclick', (function(spotMarker, i) {
return function() {
var win1 = new Ext.Panel({
floating:true,
layout: "card",
centered:false,
scroll: 'vertical',
styleHtmlContent: true,
centered: true,
width:280,
height:140,
html:'<img src="assets/images/spots/' + owt.stores.spotStore.data.map[i].data.naam.replace(/\s/g, "") + '.jpg"<div class="floatpanel"></div><h3>' + owt.stores.spotStore.data.map[i].data.naam + '</h3><p>' + owt.stores.spotStore.data.map[i].data.omschrijving + '</p></div>'
}).show()
}
})(spotMarker, i));
}
for (var i in owt.stores.groepStore.data.map) {
var groepMarker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(owt.stores.groepStore.data.map[i].data.latitude,owt.stores.groepStore.data.map[i].data.longitude),
map: this.map,
icon: 'assets/images/groepen_icon.png'
});
(groepMarker, i);
}
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
directionsDisplay.setMap(this.map);
calcRoute();
}
}
}
)]
});
function calcRoute() {
var waypts = [];
for (var i = 1; i < 9; i++) {
waypts.push({
location:new google.maps.LatLng(owt.stores.spotStore.data.map[i].data.lat, owt.stores.spotStore.data.map[i].data.lng),
stopover:true});
}
start = new google.maps.LatLng(50.80520247265613, 3.274827003479004);
end = new google.maps.LatLng(50.8252946155155, 3.2799339294433594);
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
};
Ext.reg('owt-loginpanel', owt.views.RoutePanel);
I have tried a dozen different things but i just cant get the marker to show.
I tried running your code on Google Chrome. It seems like the locationupdate event gets called only the first time after I grant the browser the permission to access my current location. After refreshing the page, the locationupdate event did not get called anymore since I had already given the browser permission to access my current location.
You could try first setting up your GeoLocation object and use it to save the user's coordinates in a variable. I believe, you don't have to use it inside the Map's afterrender function. You could try outputting your center variable with console.log() to see if you're getting the user's location correctly.
After you have the location, it shouldn't be hard to put a marker on it.