Display Multiple Markers in Array - Google Maps API - javascript

How can I clean this so that the code handles multiple listings better? I have seen some code examples that pull the marker info from an array, but I can't seem to get it to work.
The markers need to have "icon:", "url:" and "title:" attributes. The "icon:" so I can change each markers appearance, the "url:" to point through to the page dedicated to each marker and the "title" just to add the markers name on hover.
I also need the array in the script as I am not gathering it from a database or anything like that.
I am pretty green when it comes to javascript and google maps api, any help would be greatly appreciated.
function createMap(lat, lng, zoomVal) {
var mapOptions = { center: new google.maps.LatLng(lat, lng),
zoom: zoomVal,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var myLatlnglow = new google.maps.LatLng(23.654332,-79.387867);
var markerlow1 = new google.maps.Marker({
position: myLatlnglow,
icon: 'images/map-dot.png',
map: map,
url: '#',
title: 'Name'
});
google.maps.event.addListener(markerlow1, 'click', function() {
window.location.href = markerlow1.url;
});
var myLatlnglow = new google.maps.LatLng(23.688458,-79.300619);
var markerlow = new google.maps.Marker({
position: myLatlnglow,
icon: 'images/map-dot.png',
map: map,
url: '#',
title: 'Name'
});
google.maps.event.addListener(markerlow, 'click', function() {
window.location.href = markerlow.url;
});
}
var map;
function initialize() {
createMap(23.668493, -29.410812,12);
if(navigator.geolocation) {
success = function(position) {
createMap(position.coords.latitude, position.coords.longitude,13);
};
error = function() {
createMap(23.648493, -29.410812,12);
}
navigator.geolocation.getCurrentPosition(success, error);
}
}

If I were you I would make an object of objects for the sake of readability. If you must have efficiency, and want to save space and typing, replace the object with an array and address the data by index (0,1,2...)
Here's a demo
// inside function createMap(...)
...
markerData = {
bing: {
lat: 23.654332,
lng: -79.387867,
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png",
url: "http://www.bing.com/",
title: "some search engine"
},
yahoo: {
lat: 23.688458,
lng: -79.300619,
icon: "http://labs.google.com/ridefinder/images/mm_20_blue.png",
url: "http://www.yahoo.com/",
title: "Great free games"
}
};
for (markerId in markerData) {
markers[markerId] = createMarker(markerData[markerId]);
}
markers['bing'].setTitle("new title");
}
function createMarker(data) {
var myLatLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatLng,
icon: data.icon,
map: map,
title: data.title
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = data.url;
});
return marker;
}
It should also help later to save the references to the created markers, I'm using the global object markers and the same IDs.
var map;
var markers = {};
If you later need to change a marker property it is accessible through markers.
markers['bing'].setTitle("new title");

Related

Google maps v3 not a LatLngBounds or LatLngBoundsLiteral: not an Object name: "InvalidValueError"

Not the best with javascript and got some trouble with some google maps code but it is sporadic on MS Edge but consistent on Chrome and the markers will not load. On edge if you keep request the page sometimes it works but more than often fails.
ERROR: not a LatLngBounds or LatLngBoundsLiteral: not an Object name:
"InvalidValueError"
script is called using below code
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXX&libraries=places"></script>```
<script async type="text/javascript" src="{{media url='scripts/store-locator.js'}}"></script>```
require(["jquery"], function ($) {
$(document).ready(function () {
initialize();
});
var geocoder,
map,
markers = [],
infowindow = new google.maps.InfoWindow(),
bounds = new google.maps.LatLngBounds(),
marker, i;
var locations = [
{ id: 1, name: 'Store1', lat: 58.482514, lng: -1.784622 },
{ id: 2, name: 'Store2', lat: 54.687925, lng: 0.312584 }
];
function initialize() {
// set the default google map settings
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
var latlng = new google.maps.LatLng(52.727440, -1.543299);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// register the google map elements
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// register the directions display
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
addMarkers();
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
// setup control position
control = document.getElementById('store-selector');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);
control.style.display = 'block';
});
}
// add the markers from the array to the map
function addMarkers() {
$.each(locations, function (key, value) {
// create the marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(this.lat, this.lng),
map: map,
name: this.name
});
// add the marker to the cached array
markers.push(marker);
bounds.extend(marker.position);
// add the event listerner for the marker click function
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
// info window display
map.setZoom(16);
map.setCenter(marker.getPosition());
}
})(marker, i));
});
}
});```
Ok I think I have resolved it thanks to geocodezip who suggested a timing issue. was erroring on $(document).ready(function () {
initialize();
});
I've moved this to the bottom of the file and it seems to be running all good now..

Google Places API show schools and stores

Using the Google Maps API with the places library I am able to show nearby schools using the recommended method shown here.
var map;
var infowindow;
function initMap() {
var pyrmont = {lat: -33.867, lng: 151.195};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Here's a working fiddle: https://jsfiddle.net/api/post/library/pure/
The problem is that if I also want to show nearby stores as well as schools, everyone seems to recommend simply doing this:
type: ['store', 'school']
While this technically works, the problem is the map just shows a bunch of meaningless default markers with no way of knowing what it what.
So my question is: How can I change the icon for the schools and stores? Ideally I would show a different icon for each different type.
It's no different than adding custom marker in regular map.Only thing is that you need to make api calls separately for each type.So even type: ['store', 'school'] would work and you get results but there is no type specifier in the results to tell whether it's a school or shop .Also you would need to create their separate callbacks for setting their separate icons
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
icon:"http://example.com/icon.png", //<-- only this line is enough for icon
map: map,
position: place.geometry.location
});
go through this for a better understanding
Moreover every result will have a default icon (as icon property), that can also be used
var marker = new google.maps.Marker({
icon:place.icon,
map: map,
position: place.geometry.location
});

Google maps api v3 not loading in maps

I have a problem with google maps, I have tried to just to set up a normal map, but nothing works all I get is this image:
And this is my code for this:
(function ($) {
var marker;
var map;
var iconBase = 'https://maps.google.com/mapfiles/ms/icons/';
var infowindow;
function initialize() {
getCoordinate(function (location) {
setUpMap(location.latitude, location.longitude);
});
}
function setUpMap(lat, long)
{
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 8,
center: myLatlng,
mapTypeControl: false,
streetViewControl: false,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress()
{
//Resellers is a global varaible that holds all the resellers addresses
Object.keys(resellers).forEach(function(key){
var reseller = resellers[key];
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(reseller.lat, reseller.lng),
icon: iconBase + 'green-dot.png'
});
(function (marker) {
// add click event
google.maps.event.addListener(marker, 'click', function () {
if (infowindow) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
title: key,
content: '<div style="color: black; height: 150px;">' + reseller.address + '</div>'
});
infowindow.open(map, marker);
});
})(marker);
gmaerksp.push(marker);
});
}
function getCoordinate(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
var returnValue = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
};
var location = returnValue;
callback(location);
}
);
}
google.maps.event.addDomListener(window, 'load', initialize);
}(jQuery));
#map-canvas{
width: 1200px;
height: 600px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
And I have no idea why the map is not loading, the markers is loading as it should. But as you can see, the zoom tools is not correctly loading either. So you guys have any idea what is wrong? I have tested with change the div size to but it still loads the same.
Well after more debugging, I found the answer! It seems like google maps can't be inserted with wordpress shortcode. I don't know why, but as soon as I move it out to it is own template instead it works like a charm.
So if any other persons have the same problem out there, and have put there google maps in a shortcode, try to move it out from there and see if it works.

Update markers with current position on Google Map API

I am learning to use javascript right now with Rails and I'm having some issues with updating my markers according to my current position using AJAX. I believe the ready page:load is not running the updated coords that have been attached as a data-attribute, coords since the page is not technically reloading. How can I use my current position data and update it with events with longitude/latitude values?
var map;
$(document).on('ready page:load', function() {
if ("geolocation" in navigator) {
myMap.init();
var coords = $('#map-canvas').data('coords');
if (coords){
myMap.addMarkers(coords);
}
}
});
myMap.init = function() {
if(navigator.geolocation){
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
navigator.geolocation.getCurrentPosition(function(position){
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infoWindow = new google.maps.InfoWindow({
map: map,
position: pos
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map
});
map.setCenter(pos);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url:"/all_events",
method: "GET",
data: {
latitude: latitude,
longitude: longitude
},
dataType: 'script'
});
});
} else {
document.getElementById('map-canvas').innerHTML = 'No Geolocation Support.';
}
};
myMap.addMarkers = function(coords){
var image = "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"
coords.forEach(function(coord){
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(coord.latitude, coord.longitude),
map: map,
icon: image
});
});
}
In order to make your script work in the way you want please try out the following steps:
Put your foreach loop in a function and call it at the end of your successive AJAX callbacks.
Load the AJAX once the Google Maps have finished loading completely. If Google Maps library has not finished loading than you wont be able to create a Google LatLng object, this is what is probably happening over here.
Hope this would help

Marker content (infoWindow) Google Maps

I'm trying to add infoWindow's to multiple markers on a Google Map. The closest I have come is to get an infoWindow to display the last address you can see in the array, on all markers. The bit of code I have pasted below does not work, I get an "Uncaught TypeError: Cannot read property '4' of undefined". I'm sure this is a scope issue, but I'm going round in circles here and could do with some help:
var hotels = [
['ibis Birmingham Airport', 52.452656, -1.730548, 4, 'Ambassador Road<br />Bickenhill<br />Solihull<br />Birmingham<br />B26 3AW','(+44)1217805800','(+44)1217805810','info#ibisbhamairport.com','http://www.booknowaddress.com'],
['ETAP Birmingham Airport', 52.452527, -1.731644, 3, 'Ambassador Road<br />Bickenhill<br />Solihull<br />Birmingham<br />B26 3QL','(+44)1217805858','(+44)1217805860','info#etapbhamairport.com','http://www.booknowaddress.com'],
['ibis Birmingham City Centre', 52.475162, -1.897208, 2, 'Ladywell Walk<br />Birmingham<br />B5 4ST','(+44)1216226010','(+44)1216226020','info#ibisbhamcity.com','http://www.booknowaddress.com']
];
for (var i = 0; i < hotels.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(hotels[i][1], hotels[i][2]),
map: map,
icon: image,
title: hotels[i][0],
zIndex: hotels[i][2]
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
var markerContent = hotels[i][4];
infoWindow.setContent(markerContent);
infoWindow.open(map, this);
});
}
Thanks in anticipation.
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
Although this question has already been answered, I think this approach is better :
http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:
Each marker gets an "infowindow" entry :
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}

Categories

Resources