Google maps API multiple markers - google-maps

I am trying to push some markers into google maps using the following code. But it does not seem working. The map is getting centred to the right position but the I can see the markers.
var points = [<asp:literal runat="server" id="litPoints"/>];
$(document).ready(function () {
var mapCenter = new google.maps.LatLng(<asp:literal runat="server" id="litMapCentre"/>);
var options = {
zoom:<asp:literal runat="server" id="litZoomLevel"/>,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($("#monitorMap")[0], options);
GetMap(map, points);
});
function GetMap(map, mappoints) {
var image=new google.maps.MarkerImage('../Images/map/iconr.png',
new google.maps.Size(20,32),
new google.maps.Point(0,0));
for(var i=1; i < points.length; i++) {
var m=points[i];
var mylatlng=new google.maps.LatLng(m[0], m[1]);
var marker=new google.maps.Marker({
position: mylatlng,
map: map,
icon: image});
}
}

Change the second function to be like this:
function GetMap(map, mappoints) {
var image=new google.maps.MarkerImage('../Images/map/iconr.png',
new google.maps.Size(20,32),
new google.maps.Point(0,0));
for(var i=0; i < mappoints.length; i++) {
var m=mappoints[i];
var mylatlng=new google.maps.LatLng(m[0], m[1]);
var marker=new google.maps.Marker({
position: mylatlng,
map: map,
icon: image});
}
You were creating a variable called mappoints, but then referring to it as points. Also javascript arrays are zero-indexed, so if looping over them you usually need to start at 0, not 1.

Related

Algolia and google filter results based on user position

Hi I am using Google maps alongside algolia where I have an index 'locations' with 'lat' and 'lng'.
I am getting user location and watching position, I am also displaying markers from database based on lng and lat however I want to add a bit to it:
So I have followed that link:
https://www.algolia.com/doc/guides/geo-search/geo-search-overview/
And came up with:
#extends('master') #section('title', 'Live Oldham')
#section('extrafiles')
<script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50&language=en"></script>
<script type="text/javascript" src="{!! asset('js/homesearch.js') !!}"></script>
#endsection
#section('content')
<div id="map_canvas" style="height:600px;"></div>
#endsection
and js:
$(document).ready(function() {
var map;
function initializeMap(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(position) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
));
}
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition(position);
console.log(position);
}
function watchCurrentPosition(position) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position,
)
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}else{
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 100 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
var markers = [];
//alert("heelo");
var fitMapToMarkersAutomatically = true;
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
console.log(hit)
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
markers.push(marker);
}
// Automatically fit the map zoom and position to see the markers
if (fitMapToMarkersAutomatically) {
var mapBounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
mapBounds.extend(markers[i].getPosition());
}
map.fitBounds(mapBounds);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
algoliaHelper.setQueryParameter('aroundRadius', 5000).search(); // 5km Radius
});
However there are few problems with this that I don't know how to tackle:
When user is moving, it doesn't center the map on the marker.
At this moment marker jumps between location when user moves, I would like for the marker to dynamically move on the map when user moves.
I want to use algolia to dynamically set markers, so I want to show markers with 5km radius from user location, and dynamically add or remove markers that are outside it.
I can't help you much with those questions since it's mostly about how to use GMap JS lib and I'm not experienced with it. However, something else catched my eyes:
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
You should put your coordinates in the _geoloc field in order to be able to use the geo-search features. It looks like this:
_geoloc: {
lat: 40.639751,
lng: -73.778925
}

Google maps clear all markers before placing new one

I'm trying to place a marker on click in google maps along with populating input boxes with the lat and lng. I need the code to clear all the existing markers first before placing the new marker and updating the lat and lng. everything works except when I add code to try clear all the markers.
The below code works perfectly but does not clear the old markers before placing the new one.
Thank you.
Working code without clearing existing markers...
<div id="map"></div>
<script>
var map;
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker = new google.maps.Marker({
map: map,
draggable: false
});
marker.setPosition(marker_position);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
</script>
Not working code with clearing markers before adding a new one...
<div id="map"></div>
<script>
var map;
var markersArray = [];
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(event){});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker = new google.maps.Marker({
map: map,
draggable: false
});
clearOverlays();
marker.setPosition(marker_position);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
}
Thank you.
seem you have placed the code in the wrong place .. try
<div id="map"></div>
<script>
var map;
var markersArray = [];
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
clearOverlays();
marker = new google.maps.Marker({
map: map,
draggable: false
});
google.maps.event.addListener(marker,"click",function(event){});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker.setPosition(marker_position);
markersArray.push(marker);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray = [];
}
</script>

Google map in responsive map doesn't center map

I have a problem with google map. I embeeded it into responsive web. Everything's fine, map behaves responsivly, but when I change the window size, for example open the page on a mobile phone, it just cuts from the map, when it's resizing, but I need it to center the map. I need the locations be still visible and I don't know how to do it. Could anyone help me? Hope my question is comprehensible. Thanks.
API call:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
JS code:
function initialize() {
var myLatlng = new google.maps.LatLng(48.652645, 21.083107);
var mapOptions = {
zoom: 11,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
setMarkers(map, beaches);
}
var beaches = [
['xxxx'],
['xxxx']
];
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Create a bounds global variable.
Extend the bounds object when adding your markers.
On window resize, trigger a map resize and make the map fit the bounds object.
Global variable:
var bounds = new google.maps.LatLngBounds();
Extend the bounds in the setMarkers function:
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
bounds.extend(myLatLng);
}
Add this to your initialize function:
window.addEventListener("resize", resizeUI);
Create a resize function:
function resizeUI() {
google.maps.event.trigger(map, 'resize');
map.fitBounds(bounds);
}
Untested, but you get the idea...

Implementing MarkerClusterer to Google Maps API

I know this has been covered a lot before and its a simple tweak to make it work but that's making it all the more frustrating.
I'm new to Google Maps API V3 and Javascript as a whole. I've managed to make a map with markers on but I'm wanting to implement the marker clusterer feature.
My code is as follows:
<script type="text/javascript">
var markers = [
['Wathegar', 58.443420, -3.247061, '/Projects/Wathegar/', '/images/MapsIcons/operational.png'],
['Wathegar 2', 58.436726, -3.216505, '/Projects/Wathegar_2/', '/images/MapsIcons/consented.png'],
['Sibmister', 58.570869, -3.429623, '/Projects/Sibmister/', '/images/MapsIcons/planning.png'],
['Humbleburn', 54.851982, -1.651425, '/Projects/Humbleburn/', '/images/MapsIcons/planning.png'],
['Achlachan', 58.449348, -3.452797, '/Projects/Achlachan/', '/images/MapsIcons/pre-planning.png'],
['Bonwick', 53.955025, -0.227451, '/Projects/Bonwick/', '/images/MapsIcons/pre-planning.png'],
['Garton', 54.033081, -0.494127, '/Projects/Garton/', '/images/MapsIcons/pre-planning.png'],
['Hill of Lybster', 58.603081, -3.679004, '/Projects/Hill-of-Lybster/', '/images/MapsIcons/planning.png'],
['Moota', 54.710442, -3.331947, '/Projects/Moota/', '/images/MapsIcons/pre-planning.png'],
['Sherburn Stone', 54.770432, -1.4593797, '/Projects/Sherburn-Stone/', '/images/MapsIcons/pre-planning.png'],
['Spring Brook', 53.498360, -1.624646, '/Projects/Spring_Brook/', '/images/MapsIcons/pre-planning.png'],
['Sunnyside', 55.387691, -3.949585, '/Projects/Sunnyside/', '/images/MapsIcons/pre-planning.png'],
['Thacksons Well', 52.955578, -0.759824, '/Projects/Thacksons_Well/', '/images/MapsIcons/pre-planning.png'],
];
function initializeMaps() {
var latlng = new google.maps.LatLng( 56.2, -2,5);
var myOptions = {
zoom: 6,
center:latlng,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: false,
panControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
streetViewControl: false,
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var infowindow = new google.maps.InfoWindow(), marker, i;
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map,
url:markers[i][3],
icon:markers[i][4]
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
}
}
</script>
I've tried rebuilding it in the format used in this example along with a few other blogs but I don't have a good enough understanding of JS to know what I need to do.
Any help would be greatly appreciated.
Thanks!
The format of the JSON is OK, it doesn't have any effect to the MarkerClusterer.
What you are missing is to create a instance of the MarkerClusterer and to add the markers to this instance:
var mc = new MarkerClusterer(map),//MarkerClusterer-instance
marker, i;
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map,
url:markers[i][3],
icon:markers[i][4]
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
mc.addMarker(marker);//add the marker to the MarkerClusterer
}
Please note: the linked page uses the MarkerClusterer for Maps-API-V2, for V3 use this updated Version:
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js
You can also push all markers at single go to MarkerClusterer
var marker, i;
var markersArray = [];
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map,
url:markers[i][3],
icon:markers[i][4]
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
markersArray.push(marker);
}
var mc = new MarkerClusterer(map,markersArray),//MarkerClusterer-instance which add all markers to the MarkerClusterer

Close open InfoBubble when open a new (gMap v3)

I do not know what to do... I just want to close all opened infoBubbles if I'm going to open a new one. I am using the following code. Ideas? I tried a lot and googled a lot but it shouldn't be so complicated, should it? I thought to create an array and save id for the open one, but I think that there must be another, quite easier way to fix this.
$(document).ready(function(){
createmap();
function createmap(lat,lng){
var latlng = new google.maps.LatLng(50, 10);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
bounds = new google.maps.LatLngBounds();
createMarker();
}
function createMarker(){
var markers = [];
var cm = window.cm = new ClusterManager(
map,
{
objClusterIcon: new google.maps.MarkerImage('images/map/flag_cluster.png', false, false, false, new google.maps.Size(20,20)),
objClusterImageSize: new google.maps.Size(20,20)
}
);
var json = [];
var x1 = -85;
var x2 = 85;
var y1 = -180;
var y2 = 180;
for (var i=0; i<20; ++i) {
json.push(
'{'+
'"longitude":'+(x1+(Math.random()*(x2-x1)))+','+
'"latitude":'+(y1+(Math.random()*(y2-y1)))+','+
'"title":"test"'+
'}'
);
}
json = '['+json.join()+']';
// eval is ok here.
eval('json = eval(json);');
infos = [];
$.each(json, function(i,item){
var contentString = '<div id="content"><a onclick="createdetailpage('+i+');">'+item.title+'<br /></a></div>';
console.log(item.latitude);
var myLatlng = new google.maps.LatLng(item.latitude,item.longitude);
var marker = new google.maps.Marker({
position: myLatlng,
//map: map,
flat: true,
title:item.title,
//animation: google.maps.Animation.DROP,
//icon: myIcon
});
var infoBubble = new InfoBubble({
content: '<div class="phoneytext">'+contentString+'</div>'
});
google.maps.event.addListener(marker, 'click', function() {
if (!infoBubble.isOpen()) {
infoBubble.open(map, marker);
}
});
cm.addMarker(marker, new google.maps.Size(50, 50));
});
map.fitBounds(bounds);
}
});
The simplest approach to only have one infoBubble open is to only have one infoBubble and open it with different contents depending on the marker that is clicked.
InfoWindow example with custom markers (same concept applies to InfoBubble)
The InfoBubble is an OverlayView. As far as I can see, an overlaycomplete event is emitted when an overlay is added. Maybe all your InfoBubbles could listen to that event and close if the added overlay is a different one than "this".
It's just a thought, though, I haven't tried it myself. Feedback appreciated if you try it out!