Kendo UI Map - How to add marker with javascript - javascript

I have a map that a user will utilize in order to mark their position. I use geolocation and Bing layer to give them a good start. I want them to click on the map, have it recenter to the point they click, remove the existing marker, then create a new one where the map is centered.
function onClick(e) {
var resultArray = e.location.toString().split(',');
$('#map').data("kendoMap").center([parseFloat(resultArray[0]), parseFloat(resultArray[1])]);
$('#map').data("kendoMap").markers.clear();
$('#map').data("kendoMap").markers.add([parseFloat(resultArray[0]), parseFloat(resultArray[1])]);
}
The function above centers the map, removes the previous marker, and does not give an error on the ADD. However, the new marker doesn't show up.
Any help would be appreciated.
** Thanks for pointing me in the right direction. I am creating my map as a result of the geolocation. It is working now with this.
function createMap(Lat, Long) {
$("#map").kendoMap({
center: [Lat, Long],
zoom: 17,
layers: [{
type: "bing",
imagerySet: "aerialWithLabels",
key: "###MYKEY###"
}],
markers: [{
location: [Lat, Long],
shape: "pinTarget",
tooltip: {
content: "You are Here!!"
}
}],
click: onClick,
panEnd: onPanEnd
});
}
function onClick(e) {
var map = $("#map").data("kendoMap");
var loc = map.eventToLocation(e);
map.center(loc);
map.markers.clear();
map.markers.add({ location: loc });
}

You should define:
var map = $("#map").data("kendoMap");
outise the on click event
and then use map variable
map.center(loc);
map.markers.clear();
map.markers.add({location: loc});
http://dojo.telerik.com/AMoHA

Related

Google Maps using custom icon for marker sometimes doesn't show up

I am getting weird and unpredictable behavior when specifying an icon to use with google.maps.Markers. Basically, the markers show up (with default icon) if I don't specify an icon property, but if I do specify the icon property, no markers show up (although I have other case where I can get a custom icon to show, so that's why it's weird).
Here's the relevant code:
function initMap() {
var markers = route_log.map(function(segment) {
return new google.maps.Marker({
position: new google.maps.LatLng(segment.lat, segment.lng)
});
});
...calculate bounds..
var map = new google.maps.Map(document.getElementById('route_log_map_map'), {
position: bounds.getCenter(),
zoom: 15
});
...other unrelated code...
for(i=0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
This is called with:
<script src="https://maps.googleapis.com/maps/api/js?key=...key...&callback=initMap" async="" defer=""></script>
and the above results in:
Obviously that's a lousy marker to use in this case (there's almost 2000 points), so if I change the marker creation to be like this:
var markers = route_log.map(function(segment) {
return new google.maps.Marker({
position: new google.maps.LatLng(segment.lat, segment.lng),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 1
}
});
});
the markers don't show up (and there's no errors either) (note those blue circles are unrelated to this code):
EDIT
This is interesting. It works if the array I'm building the markers from has only one element, but fails to display if it has more than one. E.g. this works and displays one marker:
var route_log = [
{lat: 41.86219805, lng: -71.04886590000001}
];
var markers = route_log.map(function(segment) {
return new google.maps.Marker({
position: new google.maps.LatLng(segment.lat, segment.lng),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
}
});
});
but this displays no markers (only change is to add another element to the array):
var route_log = [
{lat: 41.86219805, lng: -71.04886590000001},
{lat: 41.87219805, lng: -71.05886590000001}
];
var markers = route_log.map(function(segment) {
return new google.maps.Marker({
position: new google.maps.LatLng(segment.lat, segment.lng),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10
}
});
});
Wow.
I have position in the options to the new google.maps.Map call. It should be center, which is required. position is not even a valid option for google.maps.MapOptions.
I blame the Google Maps API for this one. :-)

Google Maps API v3 binding events to multiple maps

I've got a page with two Google maps on, using the v3 API. Currently they have one pin each, with the same lat & long set for each pin, although one of the maps will have other pins added at a later date (when I can get this to work!) The maps are generated by looping through an object, so further maps can be added simply if needed.
What I am trying to do is bind the bounds_changed event once to both maps, to run map.setZoom() after map.fitBounds() has been run. The event, however, only binds to the last map to be set up, so does not reset the zoom on the first map.
Link to JSFiddle replicating the issue: http://jsfiddle.net/pkhb8mvz/7/
(For a more clear example of what the event is being bound to, change the event to listen on click rather than bounds_changed then try clicking on the first map and watch the zoom level change on the second map)
Any help greatly appreciated!
The problem is that the map variable is being redefined on each iteration of your loop, so by the time your event listener callback runs it will operate on the second google.maps.Map object. The simplest solution is to capture the value of the map variable on each iteration using a closure, like so:
(function (map) {
var listener = new google.maps.event.addListenerOnce(map, "bounds_changed", function () {
if (!opts.center) {
map.setZoom(opts.zoom);
};
});
}) (map);
I forked your JSFiddle to demonstrate the idea: https://jsfiddle.net/e8qbr8qL/
Created this fiddle that works based on this answer https://stackoverflow.com/a/5839041/2321666.
Apart from the function you need to add, your map variable should be an array so that there is one instance of each map.
map[i] = new google.maps.Map($(maps[i].mapElement)[0], opts);
If you need any explanation of the code please ask, but i think there is enough info about javascript closures in the post added.
You can't add a listener to multiple maps unless you keep references to all of them, currently you are only keeping a reference to the last map created.
// use function closure to associate the map with its bounds listener
addBoundsListener(map, opts, bounds);
map.fitBounds(bounds);
}
function addBoundsListener(map, opts, bounds) {
// If no center option has been specified, center the map to
// contain all pins and reset the zoom
var listener = new google.maps.event.addListenerOnce(map, "bounds_changed", function () {
if (!opts.center) {
map.setZoom(opts.zoom);
}
});
}
updated fiddle
code snippet:
var maps = {
"propertyLocation": {
"mapElement": "#map1",
"options": {
"zoom": 10,
"streetViewControl": false
},
"pins": [{
"title": "Test 1",
"lat": "52.1975331616",
"long": "0.9771180153"
}]
},
"localArea": {
"mapElement": "#map2",
"options": {
"zoom": 14,
"streetViewControl": false
},
"pins": [{
"title": "Test 2",
"lat": "52.1975331616",
"long": "0.9771180153"
}]
}
};
// Sensible defaults
var defaults = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggable: true
};
for (var i in maps) {
// Extend the options
var opts = $.extend(true, defaults, maps[i].options),
marker,
map,
bounds = new google.maps.LatLngBounds();
// Create the map
map = new google.maps.Map($(maps[i].mapElement)[0], opts);
// Create all pins
for (var p = 0; p < maps[i].pins.length; p++) {
var pin = maps[i].pins[p];
marker = new google.maps.Marker({
position: new google.maps.LatLng(pin.lat, pin.long),
map: map,
title: pin.title,
icon: pin.icon
});
// Extend the bounds of the map to contain the marker
bounds.extend(marker.position);
}
// use function closure to associate the map with its bounds listener
addBoundsListener(map, opts, bounds);
map.fitBounds(bounds);
}
function addBoundsListener(map, opts, bounds) {
// If no center option has been specified, center the map to
// contain all pins and reset the zoom
var listener = new google.maps.event.addListenerOnce(map, "bounds_changed", function() {
if (!opts.center) {
map.setZoom(opts.zoom);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div style="width: 500px; height: 500px;" id="map1"></div>
<div style="width: 500px; height: 500px;" id="map2"></div>

How to get onclick event of marker generated by getroute

In this jsfiddle is simplified version of my js: http://jsfiddle.net/Drecker/2m4kvxb8/4/ Note that interesting part of the jsfiddle is only showRoute method. And method showMarker only shows desired behavior on normal marker.
Basically I generate a route via gmap3 getroute with some waypoints. After clicking on a waypoint I need to open a small infobox with more custom information of that point - so basically somehow get onclick event of such waypoint (with some identification of that waypoint so I would be able to get proper information). I'm able to achieve desired behavior on a separate marker (as you can see in the jsfiddle - that's the fully functional separate marker on the top left), but not on the markers generated by directionrenderer.
Furthermore please note that my waypoints have stopover: false and such markers for some reason ignore (some) options like title, as you can see in jsfiddle.
Any help is very appreciated - I've tried several things none of them works.
Hope you are using the google APIs library some version, in case something like this
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places,geometry" type="text/javascript"></script>
You have one div space to show the map, say
<div id="map" style="width: 700px; height: 600px;"></div>
So you can use this for adding listener on markers
//location is an array variable where you store your co ordinates
//code to show map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(locations[0].latitude, locations[0].longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//adding listener
var marker,i;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i].city);
infowindow.open(map, marker);
}
})(marker, i));
where
marker
is the varible which will be something like this,
//adding marker
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
map: map
});
Hope from above you got some idea, might be helpful for you with your problem
There is no such option, according to the documentation and a lot of similar questions here on the stackoverflow, you can't bind click action to waypoints.
I have a workaround for that problem. The main idea is to add markers instead of waypoints and change their icon. Marker has much more options than waypoint. So I removed waypoints and added markers. Note that you have to be much more precise when adding marker's location
options without waypoints:
options: {origin: {lat:49.9, lng: 14.9},
destination: {lat: 50.1, lng: 15.1},
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
added markers with a new icon and click event:
marker:{
values:[
{latLng:[49.96485, 14.88392], data:"Waypoint1", options:{icon: "http://mt.google.com/vt/icon/name=icons/spotlight/directions_transfer_icon_10px.png&scale=1"}},
{latLng:[49.97730, 14.88185], data:"Waypoint2", options:{icon: "http://mt.google.com/vt/icon/name=icons/spotlight/directions_transfer_icon_10px.png&scale=1"}}
],
options:{
draggable: false
},
events:{
click: function(marker, event, context){
var map = $(this).gmap3("get"),
infowindow = $(this).gmap3({get:{name:"infowindow"}});
if (infowindow){
infowindow.open(map, marker);
infowindow.setContent(context.data);
} else {
$(this).gmap3({
infowindow:{
anchor:marker,
options:{content: context.data}
}
});
}
}
}
}
Here is my workaround for that problem : DEMO

jQuery/Javascript: Google Maps: How to toggle multiple pins on a map?

I have a database of locations which I want to be able to print on a map. Ideally there should be one map with multiple pins for each location you have toggled on. So click a button for location X and it shows up on the map. Click the button for location Y and it shows up on the same map. Click X again and it hides from the map.
Currently I have it so I click on X and the map gets redrawn centered around point X.
Here is the HTML for each button:
<input type='button' data-lat='38.89864400' data-long='-77.05283400'
data-when='20 Aug at 2:00am' value='Location X' class='click' />
The jQuery I'm using is:
jQuery(document).ready(
function initialize() {
jQuery("input.click").click(function() {
showOnMap(jQuery(this).data('lat'), jQuery(this).data('long'), jQuery(this).data('when'));
});
}
);
function showOnMap(lat, long, message) {
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 13,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: message
});
google.maps.event.addDomListener(window, 'load', showOnMap);
}
Is there an easy way to switch from what I have to what I want? I've searched for a while but no one seems to be asking this use case in a browser, just Android (which I'm not doing).
Thanks!
There is an example in the documentation on how to hide/show markers. In short, a marker is:
hidden by setting its map to null
showed by setting its map to map
To do so, you will need to access each marker individually. If you have a definite number of locations, it can be done by naming them with different names (eg var markerLocationX, var markerLocationY, etc). Otherwise, the markers need to be stored in an array.
Supposing you have a definite number of known locations to toggle the markers, your javascript code may look like this:
function toggleMarker(markerName) {
if (markerName.getMap() == null) {
markerName.setMap(map);
} else {
markerName.setMap(null);
}
}

Google Maps v3 Zooming specific location

i'm still learning the javascript not much pro, and this is my 1st post.
JavaScript
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
});
// Create the shared infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
var markers = [{
lat: 35.15074,
lng: -89.955992,
name: "Bob 1"
}, {
lat: 35.149425,
lng: -89.946595,
name: "Bob 2"
}, {
lat: 35.146687,
lng: -89.929837,
name: "Bob 3"
}, {
lat: 35.132264,
lng: -89.937197,
name: "Bob 4"
}];
// Create the markers
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
google.maps.event.addListener(marker, "click", function () {
openInfoWindow(marker);
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
var panorama = null;
var pin = new google.maps.MVCObject();
google.maps.event.addListenerOnce(infowindow, "domready", function () {
panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true
});
panorama.bindTo("position", pin);
});
// Set the infowindow content and display it on marker click.
// Use a 'pin' MVCObject as the order of the domready and marker click events is not garanteed.
function openInfoWindow(marker) {
title.innerHTML = marker.getTitle();
pin.set("position", marker.getPosition());
infowindow.open(map, marker);
}
}
I had the 4 different places, then i need the 4 webpages to add, how to i tell the browser that i want zooming the specific location. let's say i wanted to zooming at "Bob 1".
Then i rename the webpage as bob1.html. Whenever i click the bob1.html the webpage will zooming zoom: 15 and the marker is center on the map
You don't need to have four different pages unless this is part of the spec?
To set the position and zoom level of the map simply call:
map.setCenter(yourLatLngOrMarkerPosition);
And to set the zoom level:
map.setZoom(yourZoomLevel);
These could be set at any point after the instantiation of the map so perhaps on button clicks or after a period of time?
Hope this helps.
Edit To take into account your requirements (mentioned in the comments) I would submit the relevant url post parameters upon clicking the link. Within the initialize function of each map page you will then need to read these out using something similar to Here (though this uses jQuery) and set the map options as appropriate.
Edit You can read the url post parameters out with php and then echo them in the appropriate places within the google maps calls.
For Example:
map.setZoom(<?php echo $_GET['urlZoomParam'];?>);
Etc.
Some general PHP/MYSQL/Google Maps stack docs: https://developers.google.com/maps/articles/phpsqlajax_v3 https://developers.google.com/maps/articles/phpsqlsearch_v3 http://theoryapp.com/online-store-locator-using-php-mysql-and-google-maps/

Categories