I want to set different hovers for different marker icons i use on my map.
This is my marker icon array
//Marker Icons
var markerIcon = {
unvisitedMarker: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(15, 15)
},
unvisitedMarkerHover: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(30, 0),
anchor: new google.maps.Point(15, 15)
},
activeMarker: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(60, 0),
anchor: new google.maps.Point(15, 15)
},
visitedMarker: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(90, 0),
anchor: new google.maps.Point(15, 15)
},
visitedMarkerHover: {
url: 'img/marker.png',
size: new google.maps.Size(30, 30),
origin: new google.maps.Point(120, 0),
anchor: new google.maps.Point(15, 15)
}
I got all icons in one sprite.
I want to set the hover effect for the 'unvisitedMarker' with 'unvisitedMarkerHover' and for 'visitedMarker with 'visitedMarkerHover'. If the marker has the 'activeMarker' icon it should not get a hover effect.
My Problem with this is - i don't know how to set the "if" requirement for that.
//marker hover effect
marker.addListener('mouseover', function() {
if (???) { ... }
});
marker.addListener('mouseout', function() {
if (???) { ... }
});
After that i know i can set the icon with:
marker.setIcon(markerIcon['unvisitedMarker']);
So if someone could help me with the if requirement - that would be awesome!
This one is not that simple. Since I don't have the details such as the URL to your images, I created a sample application in which we have at least 90% similarity. Important: Please don't use the images I've used to avoid copyright issues.
First, I've created public variables: map, markers. "markers" is an empty array.
var map;
var markers = [];
I've also created my own version of markerIcon object.
var markerIcon = {
url : 'http://oi68.tinypic.com/30idv0z.jpg',
unvisitedMarkerHover: 'http://oi65.tinypic.com/jgo3r8.jpg',
originlUrl: 'http://oi68.tinypic.com/30idv0z.jpg',
visitedMarkerHover: 'http://oi65.tinypic.com/ejbn88.jpg',
status: {
unvisitedMarker : {
statusName: 'unvisitedMarker',
},
activeMarker : {
statusName: 'activeMarker',
},
visitedMarker : {
statusName: 'visitedMarker',
}
}
};
I've used a coordinate in San Francisco for my map's center and for Google Maps Javascript API Places Library. I've used Nearby Search as a Place Search and used San Francisco's coordinate for the location property. The radius is set to 500 (measured in meters). This is essential as a combination of the location property - specifying the center of the circle as a LatLng object. For the types, i restricted it only to stores. To learn more about supported types, please check list of supported types.
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLatLng,
radius: '500',
type: ['store']
}, callback);
In Nearby Search callback, it returns an array of results. This is what I did:
function createMarker(place, markerId) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
id: markerId,
map: map,
position: placeLoc,
title: 'Hello World!',
anchor: new google.maps.Point(15, 15),
icon: {
url : markerIcon.url,
},
currentStatus: '',
status: markerIcon.status.unvisitedMarker.statusName,
size: new google.maps.Size(30,30),
});
markers.push(marker);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i],i);
}
}
}
I created a createMarker() function that accepts two arguments: the
place object, and markerId.
What the function does is it creates a new Google Maps Javascript
API
Marker
and then set the property and its values accordingly. And also, after
creating the new "marker" object, it will be pushed in to
markers array.
You will also notice that I've added custom properties:
currentStatus, and status. This will play a very important role in
our mouse events.
Since the callback results is an array, I iterate through each array
and called createMarker() function.
This is where the fun begins, in createMarker(), I've also added lines for Google Maps Javascript API Events. This is what I did on my end. Whenever there's a mouseover on a marker, it checks first the currentStatus property of the mouseovered marker. If the currentStatus is an empty string '', it will do another checking for the status property. If the status is 'unvisited', the current icon will now change to a new one. When a mouseout has been detected, the new icon will change to the original one.
Meanwhile, when a marker is clicked, the currentStatus property will be updated to "activeMarker" and then the "status" property is changed to "visitedMarker" as well. You will notice that if the marker has an "activeMarker" currentStatus, nothing will happen when there's a mouseover.
In order to remove the "activeMarker" currentStatus, you will have to click another marker. The "activeMarker" now is transferred to this "another marker". You will also notice that there's a new mouseover effect on the previous marker because I've set a new icon if the marker's status is "unvisitedMarker". You can all find all icon URLs in the markerIcon object.
google.maps.event.addListener(marker, 'mouseover', function() {
if ( this.currentStatus !== markerIcon.status.activeMarker.statusName ) {
if ( this.status === markerIcon.status.unvisitedMarker.statusName ) {
this.setIcon(markerIcon.unvisitedMarkerHover);
} else {
this.setIcon(markerIcon.visitedMarkerHover);
}
this.setPosition(this.position);
console.log(this.currentStatus, this.status, this.id);
}
});
google.maps.event.addListener(marker, 'mouseout', function() {
this.setIcon(markerIcon.originlUrl);
});
google.maps.event.addListener(marker, 'click', function() {
for ( var i = 0; i < markers.length; i++ ) {
markers[i].currentStatus = '';
}
this.currentStatus = markerIcon.status.activeMarker.statusName;
this.status = markerIcon.status.visitedMarker.statusName;
console.log(this.currentStatus, this.status);
});
Whole code below:
var map;
var markers = [];
var markerIcon = {
url : 'http://oi68.tinypic.com/30idv0z.jpg',
unvisitedMarkerHover: 'http://oi65.tinypic.com/jgo3r8.jpg',
originlUrl: 'http://oi68.tinypic.com/30idv0z.jpg',
visitedMarkerHover: 'http://oi65.tinypic.com/ejbn88.jpg',
status: {
unvisitedMarker : {
//origin: new google.maps.Point(0, 0),
statusName: 'unvisitedMarker',
},
activeMarker : {
//origin: new google.maps.Point(60, 0),
statusName: 'activeMarker',
},
visitedMarker : {
//origin: new google.maps.Point(90, 0),
statusName: 'visitedMarker',
},
}
};
function initMap() {
var myLatLng = {lat: 37.773972, lng: -122.431297};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: myLatLng
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: myLatLng,
radius: '500',
type: ['store']
}, callback);
}
function createMarker(place, markerId) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
id: markerId,
map: map,
position: placeLoc,
title: 'Hello World!',
anchor: new google.maps.Point(15, 15),
icon: {
url : markerIcon.url,
},
currentStatus: '',
status: markerIcon.status.unvisitedMarker.statusName,
size: new google.maps.Size(30,30),
});
markers.push(marker);
google.maps.event.addListener(marker, 'mouseover', function() {
if ( this.currentStatus !== markerIcon.status.activeMarker.statusName ) {
if ( this.status === markerIcon.status.unvisitedMarker.statusName ) {
this.setIcon(markerIcon.unvisitedMarkerHover);
} else {
this.setIcon(markerIcon.visitedMarkerHover);
}
this.setPosition(this.position);
//console.log(this.currentStatus, this.status, this.id);
}
});
google.maps.event.addListener(marker, 'mouseout', function() {
this.setIcon(markerIcon.originlUrl);
});
google.maps.event.addListener(marker, 'click', function() {
for ( var i = 0; i < markers.length; i++ ) {
markers[i].currentStatus = '';
}
this.currentStatus = markerIcon.status.activeMarker.statusName;
this.status = markerIcon.status.visitedMarker.statusName;
});
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i],i);
}
}
}
/* 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;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap"
async defer></script>
Hope this application could help and happy coding!
Related
I'm developing a web app with angular 6. I integrated google maps but marker click event is returning me an error.
Help me, thanks in advance.
import { } from '#types/googlemaps';
#ViewChild('whereMap') gmapElement: any;
map: google.maps.Map;
marker: google.maps.Marker;
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
let marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
}
map initialized and marker is working fine, but im unable to fire click event.
i have called the initMapp() in ngOnInit().
The navigator.geolocation.getCurrentPosition is asynchronous, you are likely meeting a race condition. You should move google.maps.event.addListener inside geolocation callback, otherwise you can try to assign event listener before the marker element was created.
Google Maps JavaScript API error message ERROR TypeError: Cannot read property '__e3_' of undefined typically means that you try to assign event to non-existing DOM element.
Try the following
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
this.marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
I hope this helps!
So in my Rails app I am building out a region show page with multiple locations. Users are able to insert new locations and map markers need to be dynamically placed based on the latitude and longitude that they enter. In my Region show page I have the following:
<div class="container-fluid">
<div class="row">
<div class="banner" id="region-banner" data-region-name="<%=#region.name.downcase%>">
<script>document.addEventListener('DOMContentLoaded',app.regions);</script>
Then in my region.js file I have the following:
import { tns } from 'tiny-slider/src/tiny-slider.module';
import { mapStyle } from './styles/mapStyle';
app.regions = () => {
function init() {
startGoogleMap();
}
let startGoogleMap = () => {
let map = new google.maps.Map(document.getElementById('region-banner'), {
zoom: 3,
minZoom: 3,
disableDefaultUI: true,
gestureHandling: 'cooperative',
styles: mapStyle
});
var mapElement = document.getElementById('region-banner');
const regionName = mapElement.getAttribute('data-region-name');
let bounds = new google.maps.LatLngBounds();
let promise = $.getJSON('/locations.json');
promise.done(function(data) {
return $.each(data, function() {
return new google.maps.Marker({
position: {
lat: parseFloat(data.lat),
lng: parseFloat(data.lng) },
map: map,
icon: "/marker.png"
});
});
});
console.log(promise);
map.fitBounds(bounds);
};
return init();
};
Then in my controller I have:
def show
#locations = Location.all
respond_to do |format|
format.json { render json: #locations }
format.html
end
end
So no real errors are applying however...nothing appears. The console shows the responseText:“[{“id”: 5, “name”: “Chicago”, “abbreviation”: “CHI”, “lat”: “44.222”, “lng”: “-22.111”}, {“id”: 6, “name”: “Frankfort”, “abbreviation”: “FKT”, “lat”: “41.3232”, “lng”: “-19.5221”} ]”. Which really on this page I should only need/use the first.
Shouldn't it also be applying the markers at this stage since I put in the position?
this is the code responsible for setting your Markers.
I would focus on understanding why promise.done() does not run create the new google.maps.Marker() for each row in your (data) from your response.
Maybe the problem is connected to the /marker.png
promise.done(function(data) {
return $.each(data, function() {
return new google.maps.Marker({
position: {
lat: parseFloat(data.lat),
lng: parseFloat(data.lng) },
map: map,
icon: "/marker.png"
});
});
});
I have a little problem and I can't find the solution; maybe someone will know how to fix it.
I have code below where Google StreetViewPanorama and everything (drag, zoom) is working okay. But when I init other image in this object, after the image loads in the object, it stops working: no zooming, edges are displayed, dragging is half-working.
Destroying object before changing image doesn't work.
Maybe is there some method to update this object?
function initPano() {
// Set up Street View and initially set it visible. Register the
// custom panorama provider function. Set the StreetView to display
// the custom panorama 'reception' which we check for below.
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('map'), {
pano: 'reception',
visible: true,
panoProvider: getCustomPanorama
}
);
}
// Return a pano image given the panoID.
function getCustomPanoramaTileUrl(pano, zoom, tileX, tileY) {
// Note: robust custom panorama methods would require tiled pano data.
// Here we're just using a single tile, set to the tile size and equal
// to the pano "world" size.
return 'img/pano-1.jpg'; // <----------- HERE
}
// Construct the appropriate StreetViewPanoramaData given
// the passed pano IDs.
function getCustomPanorama(pano, zoom, tileX, tileY) {
if(pano === 'reception') {
return {
location: {
pano: 'reception',
description: 'Description'
},
links: [],
// The text for the copyright control.
copyright: 'Imagery (c) 2010 Google',
// The definition of the tiles for this panorama.
tiles: {
tileSize: new google.maps.Size(1024, 512),
worldSize: new google.maps.Size(1024, 512),
// The heading in degrees at the origin of the panorama
// tile set.
centerHeading: 105,
getTileUrl: getCustomPanoramaTileUrl
}
};
}
}
I figured out something like this, and for now it's working corectly..
var panorama;
function initialize() {
var panoOptions = {
pano: 'sfera-4',
visible: true,
panoProvider: getCustomPanorama
}
panorama = new google.maps.StreetViewPanorama(
document.getElementById('map'),
panoOptions
);
}
function getCustomPanoramaTileUrl(pano,zoom,tileX,tileY) {
return 'i/'+pano+'s.jpg';
}
function getCustomPanorama(pano,zoom,tileX,tileY) {
switch(pano) {
case 'sfera-4':
return {
location: {
pano: 'sfera-4',
description: 'Sfera 4'
},
copyright: 'Description',
tiles: {
tileSize: new google.maps.Size(4096,2048),
worldSize: new google.maps.Size(4096,2048),
centerHeading: 0,
getTileUrl: getCustomPanoramaTileUrl
}
};
break;
case 'sfera-7':
return {
location: {
pano: 'sfera-7',
description: 'Sfera 7'
},
copyright: 'Description',
tiles: {
tileSize: new google.maps.Size(4096,2048),
worldSize: new google.maps.Size(4096,2048),
centerHeading: 0,
getTileUrl: getCustomPanoramaTileUrl
}
};
break;
}
}
function setMap(id) {
panorama.setPano('sfera-'+id);
}
for changing image I just calling setMap(7)
I have been trying to use google map with angularJS.
I have learned how to use it through https://angular-ui.github.io/angular-google-maps/#!/.
Everything goes well.
For each marker, I can show InfoWindow which has an element information of myList.
But I have got stuck in InfoWindow with cluster.
When cluster is clicked, I want to show the information list of markers in cluster.
Even I can't show simple InforWindow when clicking the cluster.
Below sources are my code.
Please tell me if it is not enough to solve my problem.
Please tell me what is wrong and how to solve this.
Have a nice day.
* javascript
$scope.map.map = {
center: { latitude: $scope.map.myList[0].lat, longitude: $scope.map.myList[0].lng },
zoom: 17,
events : {
tilesloaded: function (map) {
$scope.$apply(function () {
google.maps.event.addDomListener(window, 'resize', function() {
var lat = $scope.map.myList[$scope.map.markerPosition-1].lat;
var lng = $scope.map.myList[$scope.map.markerPosition-1].lng;
var center = new google.maps.LatLng(lat, lng);
map.setCenter(center);
});
});
}
},
markersEvents: {
click: function(marker, eventName, model) {
model.show = !model.show;
return;
}
},
clusterOptions : { // options of cluster
gridSize: 40,
ignoreHidden: true,
zoomOnClick : false,
averageCenter : true,
styles: [
{
height: 53,
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m3.png",
width: 53,
textColor : 'white'
}
]
},
clusterEvent: { // when cluster's clicked
click: function(map, markers) {
var contentString = 'ABCD';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, markers);
return;
}
}
};
$scope.map.options = {
streetViewControl : false
};
$scope.map.markers = [];
* html
<ui-gmap-google-map center='map.map.center' zoom="map.map.zoom" options="map.options" events="map.map.events">
<ui-gmap-markers models="map.markers" coords="'self'" icon="a" events="map.map.markersEvents" options="'options'"
doCluster="true" clusterOptions="map.map.clusterOptions" clusterEvents="map.map.clusterEvent">
<ui-gmap-windows show="show">
<div ng-non-bindable>{{id}}</div>
</ui-gmap-windows>
</ui-gmap-markers>
Answer myself.
var infoWindowOptions = {
content: "asdfasdf"
};
var infowindow = new google.maps.InfoWindow(infoWindowOptions);
infowindow.open(map.map_, *marker*);
My code sets the zoom level for my desktop browser, but my device is SUPER zoomed in (like zoom level 20). How can I get the zoom to apply to both?
function CreateMap() {
Data.$paymentMap.gmap({'center': GetLatLng(), 'zoom' : 15}).bind('init', function(evt, map) {
Data.$paymentMap.gmap('watchPosition', function(position, status) {
if (status === 'OK') {
Data.$paymentMap.gmap({'zoom' : 15});
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var userMarker = Data.$paymentMap.gmap('get', 'markers > user' );
if (!userMarker) {
Data.$paymentMap.gmap('addMarker', { 'id': 'user', 'position': GetLatLng(), 'bounds': true, icon: '/images/trunk/icon/icon-map-marker.png' });
} else {
userMarker.setPosition(latlng);
map.panTo(latlng);
}
}
});
});
}