completely destroy marker on gmap3 - google-maps

I am trying to let a user drop up to 10 markers and remove them onClick. I also have it updating a "div" with the coordinates of the markers on the map when a user adds a marker or drags. I have everything working except for when the user deletes a marker, it's still seems to be on the map when I loop through the markers. Any idea what I'm doing wrong?
jsFiddle: jsfiddle.net/ryanverdel/WRyrJ/
Code:
$(document).ready(function () {
var markerCount = 0;
$("#test1").gmap3({
map: {
options: {
center: [-2.2214281090541204, -78.695068359375],
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
disableDoubleClickZoom: true,
streetViewControl: false,
},
events: {
click: function (map, event) {
if(markerCount < 10){
$(this).gmap3(
{
marker: {
latLng: event.latLng,
options:{
draggable: true,
animation: google.maps.Animation.DROP,
},
events: {
click: function(marker) {
marker.setMap(map);
marker.setMap(null);
marker = null;
delete marker;
console.log(marker);
markerCount--;
},
dragend: function(marker) {
$("#inputArray").empty();
setTimeout(function(){
var markers = $("#test1").gmap3({
get: {
all: true
}
});
$.each(markers, function(i, marker){
$("#inputArray").append('<p>{"latitude":' + marker.position.lat() +', '+ '"longitude":' + marker.position.lng() +'},'+'</p>');
});
}, 400);
}
},
},
});
markerCount++;
$("#inputArray").empty();
setTimeout(function(){
var markers = $("#test1").gmap3({
get: {
all: true
}
});
$.each(markers, function(i, marker){
$("#inputArray").append('<p>{"latitude":' + marker.position.lat() +', '+ '"longitude":' + marker.position.lng() +'},'+'</p>');
});
}, 400);
}
else{
return false;
};
}
}
}
});
});

This sort of thing is maybe less than straightforward in gmap3. You need a slightly different mindset compared with that required for the direct google.maps API.
Thee main poitns :
You need to provide the markers with an id, name or tag
You need to remove the marker with clear
You need to make judicious use of callbacks (the gmap3 way).
Here's your code unravelled into a set of functions, with the necessary fixes applied
$(document).ready(function () {
var mapOpts = {
center: [-2.2214281090541204, -78.695068359375],
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
disableDoubleClickZoom: true,
streetViewControl: false,
};
function genId() {
return '' + (new Date()).getTime();
}
function addMarker(map, event) {
if (markerCount < 10) {
var uid = genId();
$(this).gmap3({
marker: {
latLng: event.latLng,
options: {
draggable: true,
animation: google.maps.Animation.DROP
},
events: {
click: function() {
clearMarker(uid);
},
dragend: listMarkers
},
id: uid
}
});
markerCount++;
listMarkers();
} else {
return false;
};
}
function listMarkers() {
$("#test1").gmap3({
get: {
all: true,
callback: function(results) {
$("#inputArray").empty();
$.each(results, function (i, marker) {
$("#inputArray").append('<p>{"latitude":' + marker.position.lat() + ', ' + '"longitude":' + marker.position.lng() + '},' + '</p>');
});
}
}
});
}
function clearMarker(uid) {
$('#test1').gmap3({
clear: {
id: uid,
callback: function() {
listMarkers();
markerCount--;
}
}
});
}
var markerCount = 0;
$("#test1").gmap3({
map: {
options: mapOpts,
events: {
click: addMarker
}
}
});
});
DEMO

Related

set the right link on each marker

I have a map with multiple markers. Everything works fine, but I can't set the links for each marker with click function. It's always the same value.
(p.s. I'm using the gmap3 plugin)
My link information is into json like a .link.link.
$('#search-map-btn').on('click', function () {
$.ajax({
url: "/",
data: $('#dir-search-form').serializeArray(),
type: "POST",
context: document.body
}).done(function (json) {
var mapDiv = $("#map-container");
mapDiv.gmap3({
clear: {}
});
for (key in json) {
var lon = json[key].coords.lon;
var lat = json[key].coords.lat;
var link = json[key].link.link;
//all map parameters
mapDiv = jQuery("#map-container");
mapDiv.height(390).gmap3({
map: {
options: {
"draggable": false,
"mapTypeControl": true,
"mapTypeId": google.maps.MapTypeId.ROADMAP,
"scrollwheel": true,
"panControl": true,
"rotateControl": true,
"scaleControl": true,
"streetViewControl": true,
"zoomControl": true,
"center": [56.9475, 24.106944],
"zoom": 8
}
},
marker: {
values: [{
latLng: [lat, lon]
}],
options: {
"animation": google.maps.Animation.DROP,
"draggable": false,
"clickable": true,
"icon": "<?php bloginfo('template_directory'); ?>/images/new/gmap.marker.png",
},
events: {
click: function () {
document.location.href = json[key].link.link
}
},
},
});
}
});
});
Did that by including cycle before function(key) -> "for(key in json){... })(key);"
$('#search-map-btn').on('click', function(){
$.ajax({
url: "/",
data: $('#dir-search-form').serializeArray() ,
type: "POST",
context: document.body
}).done(function(json){
var mapDiv = $("#map-container");
mapDiv.gmap3({ clear: { } });
for(key in json){
(function(key){
var lon = json[key].coords.lon;
var lat = json[key].coords.lat;
var link = json[key].link;
//all map parameters
mapDiv = jQuery("#map-container");
mapDiv.height(390).gmap3({
map: {
options: {
"draggable": true
,"mapTypeControl": true
,"mapTypeId": google.maps.MapTypeId.ROADMAP
,"scrollwheel": true
,"panControl": true
,"rotateControl": true
,"scaleControl": true
,"streetViewControl": true
,"zoomControl": true
,"center": [56.9475, 24.106944]
,"zoom": 8
}
},
marker:{
values:[
{latLng:[lat, lon], link:[link]}
],
options:{
"animation": google.maps.Animation.DROP,
"draggable": false,
"clickable": true,
"icon": "<?php bloginfo('template_directory'); ?>/images/new/gmap.marker.png",
},
events: {
click: function(){document.location.href = json[key].link.link},
}
});
})(key);

How to retrieve data from a store in Sencha Touch

Now I have my store: stuStore set up which contains some mock-up data.
I have another page which is a Google Map.
Student data structure: {name, geolocation,value, etc....}
I would like to display each of students info based on their locations which is inside of stuStore onto the google Map.
Here is the code:
Ext.define('myapp.view.Main', {
extend: 'Ext.tab.Panel',
xtype: 'main',
fullscreen: true,
requires: [
'Ext.TitleBar',
'Ext.Video',
'Ext.Map',
'Ext.Panel',
'Ext.tab.*',
'Ext.*'
],
config: {
tabBarPosition: 'bottom',
items: [
{
title: 'myapp',
iconCls:'maps',
xtype: 'map',
useCurrentLocation: true,
store: 'myapp.store.stuStore'
}
How can I do it?
Update 1
var mapdemo = Ext.create('Ext.Map', {
mapOptions: {
center: new google.maps.LatLng(-37.73228, 144.86900), //nearby San Fran
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
}
},
title: 'MyApp',
iconCls: 'maps',
fullscreen: true,
xtype: 'map',
id: 'mainMap',
useCurrentLocation: false,
listeners: {
maprender: function (comp, googleMap) {
var store, latlng, marker;
store = Ext.getStore('myapp.store.stuStore');
store.each(function (record, index, length) {
latlng = new google.maps.LatLng(record.get('Lat'), record.get('Lng'));
marker = new google.maps.Marker({
position: latlng,
map: this
});
});
}
}
}),
infowindow = new google.maps.InfoWindow({
content: 'Sencha HQ'
});
Ext.define('myapp.view.Main', {
extend: 'Ext.tab.Panel',
xtype: 'main',
fullscreen: true,
config: {
tabBarPosition: 'bottom',
items: [mapdemo],
}
});
This is my updated code in view\Main.js
But I don't get any markers and it keeps throwing an error:
Uncaught TypeError: Cannot call method 'each' of undefined
Incidentally, the icon on the toolbar which is docked at bottom of the screen is gone as well.
What can I try next?
You can create markers based on store records by looping through them in the maprender event callback like this:
Ext.define('myapp.controller.MapController', {
extend: 'Ext.app.Controller',
config: {
refs: {
mapComponent: 'main map'
},
control: {
mapComponent: {
maprender: 'onMaprender',
}
}
},
onMaprender: function(mapComponent, googleMap) {
var store, latLng, marker;
// Get store
store = Ext.getStore('myapp.store.stuStore')
// On each store record
store.each(function(record, index, length) {
// Get position
latLng = new google.maps.LatLng(record.get('lat'), record.get('lng'));
// Create marker
marker = new google.maps.Marker({
position: latLng,
map: googleMap
});
});
}
});
Have a look at this Sencha Fiddle I put together.

"dragend" method for marker in Google Maps

I have a problem with my marker in Google Maps. This is my code:
var map;
var geocoder;
var current;
var styles = [
{
stylers: [
{ hue: "#00c0eb" },
{ saturation: -10 }
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
{ lightness: 100 },
{ visibility: "simplified" }
]
},{
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "on" }
]
}
];
var NewEventMarker;
function changeMarkerPosition(marker, ll) {
marker.setPosition(ll);
}
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.BOTTOM_CENTER
},
scaleControl: false,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
map.setOptions({styles: styles});
google.maps.event.addListener(map, 'click', addNewEvent);
}
function codeAddress() {
var address = "London";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var image = new google.maps.MarkerImage("/img/markers/user-m.png",
new google.maps.Size(32.0, 49.0),
new google.maps.Point(0, 0),
new google.maps.Point(16.0, 24.0)
);
var marker = new google.maps.Marker({
map: map,
icon: image,
flat: false,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function addNewEvent(event){
var NEMlatLng;
if(NewEventMarker == undefined){
NewEventMarker = new google.maps.Marker({
map: map,
draggable: true,
icon: "/img/markers/marker-add.png",
position: event.latLng,
title: "Добавить событие"
});
} else {
changeMarkerPosition(NewEventMarker, event.latLng);
}
google.maps.event.addListener(NewEventMarker,'dragend',function(event) {
alert(event.latLng);
});
}
The idea of this code is when user clicks on a map, start work function - addNewEvent, and as you can see, if there is already exists "NewEventMarker", it just moves this marker to a place where user clicks, and if there are no marker, it creates. So if you try my code you can see, that if i click, for example two or three times on a map, marker will moves, but when i drag my marker, starts work function that assigned to 'dragend' event. But it will be works so many times, how much i clicked on a map. How can i fix it?
When i try to add google.maps.event.addListener(NewEventMarker,'dragend'....... to other places in my code i get an error: Cannot read property '_e3' of undefined
Please help me ;)
Evgeny, you did almost everything right but for each click you attach new event handler for dragend. Because of that you got several dragend events and for each event one alert.
Solution is to just move event handler to if statement and add event listener only in case if NewEventMarker is created (only first time):
function addNewEvent(event){
var NEMlatLng;
if (NewEventMarker == undefined){
NewEventMarker = new google.maps.Marker({
map: map,
draggable: true,
icon: "marker-add.png",
position: event.latLng,
title: "Добавить событие"
});
google.maps.event.addListener(NewEventMarker, 'dragend', function(event) {
alert(event.latLng);
});
} else {
changeMarkerPosition(NewEventMarker, event.latLng);
}
}

Sencha Touch 2: Google Maps Directions Route won't show

I'm using a view to show a location on a map with a small form below it to grab the users address if they want directions. The map renders initially as I want. There is a controller to handle tapping the button and updating the display with the route. I can see that it is successfully retrieving the route information. It's just not updating the display to show it. What am I missing?
Here's the view:
var tcmlatlng = new google.maps.LatLng(38.898748, -77.037684);
Ext.define('VisitTCMIndy.view.Directions',{
extend: 'Ext.Panel',
requires: [
'Ext.form.Panel',
'Ext.Map'
],
config: {
layout: 'vbox',
items: [
{
xtype: 'map',
useCurrentLocation: false,
flex: 3,
mapOptions: {
center: tcmlatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
listeners: {
maprender: function(map,gmap,options){
var homemarker = new google.maps.Marker({
position: tcmlatlng,
map: gmap
});
}
}
},
{
xtype: 'formpanel',
id: 'directionsform',
flex: 1,
items:[
{
xtype: 'textfield',
name: 'address',
label: 'Address',
},
{
xtype: 'button',
ui:'action',
text: 'Get Directions'
}
]
}
]
}
});
Here's the controller
Ext.define('VisitTCMIndy.controller.Directions',{
extend: 'Ext.app.Controller',
config: {
control: {
dButton: {
tap: 'loaddirections'
}
},
refs: {
dButton: '#directionsform button[ui=action]',
tcmmap:'map',
addfield:'textfield[name=address]'
}
},
loaddirections: function(dbutton){
console.log('loaddirections');
var gmap = this.getTcmmap();
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(gmap.map);
var tcmadd = "1600 Pennsylvania Ave, Washington, DC";
var originadd = this.getAddfield().getValue();
var request = {
origin: originadd,
destination: tcmadd,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status){
console.log(status);
if(status = google.maps.DirectionsStatus.OK){
console.log(result);
directionsDisplay.setDirections(result);
}
});
}
});
I was referencing the map incorrectly. I was trying to reference it directly instead of using the getter. So anywhere you see 'gmap.map' it should read 'gmap.getMap()'.

Googlemaps getting offset

Hey everyone anyone ever tried similar incident
its inside a jquery tab system and it works alone or any other place at the website but when inside a tab its getting this offset in some weird manner!
if you tried it or have a solution please post it
<% if (RentalCaseMap.Any()) { %>
<div id="Kort" class="tab-content">
<div id="rental_map_canvas" style="width:656px; height:270px"></div>
<script type="text/javascript" src="/scripts/rentalmap.js"></script>
</div>
<% } %>
....
<input type="hidden" id="HiddenGeoLat" value="<%=CurrentContent.GeoLat %>" />
<input type="hidden" id="HiddenGeoLng" value="<%=CurrentContent.GeoLng %>" />
Then script file
$(window).load(function () {
initialize();
});
function initialize() {
var jeudanStyles = [{ featureType: "all", elementType: "all", stylers: [{ saturation: -99}]}];
var jeudanMapType = new google.maps.StyledMapType(jeudanStyles,
{ name: "Jeudan" });
var myOptions = {
zoom: 16,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.BOTTOM_CENTER
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.LEFT_CENTER
},
scaleControl: false,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_CENTER
},
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.BOTTOM_CENTER
}
};
if (document.getElementById("rental_map_canvas") != null) {
var map = new google.maps.Map(document.getElementById("rental_map_canvas"), myOptions);
map.mapTypes.set('jeudan_map', jeudanMapType);
map.setMapTypeId('jeudan_map');
var locations = [
{ lat: 55.680884, lng: 12.581577, content: '<div class="jeudanparkering">Addresse: Gammel Mønt 1 - 3<br />Mandag - lørdag 06.30-21.00.<br />Mere info...</div>' }
];
var marker, i;
var image = new google.maps.MarkerImage('/images/maps-logo-small.png', new google.maps.Size(35, 40), new google.maps.Point(0, 0), new google.maps.Point(35, 40));
var shadow = new google.maps.MarkerImage('/images/maps-logo-shadow-small.png', new google.maps.Size(74, 37), new google.maps.Point(0, 0), new google.maps.Point(34, 37));
var shape = {
coord: [1, 1, 1, 40, 35, 40, 35, 1],
type: 'poly'
};
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng($("#HiddenGeoLat").val(), $("#HiddenGeoLng").val()), /*new google.maps.LatLng(locations[i].lat, locations[i].lng),*/
map: map,
shadow: shadow,
icon: image,
animation: google.maps.Animation.DROP,
shape: shape
});
marker.content = locations[i].content;
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(this.content);
infowindow.open(map, this);
});
map.setCenter(marker.position);
}
};
}
You need to call google.maps.event.trigger(map, 'resize');
$("#liKort").click(function () {
google.maps.event.trigger(map, 'resize');
map.setCenter(marker.position);
});