I have a Google Maps script in this format:
function initMap()
{
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {center: {lat: 45.9, lng: 25.0}, zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP, disableDoubleClickZoom:true, scrollwheel:false, ...});
var marker = new google.maps.Marker({position: {lat:46.1, lng:25.4}, map:map, icon:'../images/Marker.png});
}
I'd like to know how the var marker part of the script must look like if there were more than one points to be displayed. Note: I have seen JavaScript examples on StackExchange which use arrays etc. - one of the best is here: Google Maps Script - but I want my script to use the format above, which is very simple.
The google.maps.Marker class can only create a marker for a single point at at time, so you'll need some way to repeat that for all your points.
I'd say have an array of objects, each of which has the latitude and longitude values as separate properties. And any other properties you might want to associate with all your points, such as titles and icons. e.g.
var places = [
{
latitude: 46.1,
longitude: 25.4
title: "Place 1",
icon: "blue.png"
},
{
latitude: 54.1,
longitude: 0.0
title: "Place 2"
icon: "red.png"
},
// etc
];
Then when you want to create the markers, just loop over the array:
for (var i = 0; i < places.length; i++) {
marker = new google.maps.Marker({
position: {lat:places[i].latitude, lng: places[i].longitude},
title: places[i].title,
map: map,
icon: '../images/' + places[i].icon
});
}
Related
My code puts a marker on the map each time I click on it.
The objective is to get each time marker's lat/lon coordinates together with pixel coordinates. So far I've been successful only in getting lat/lon coord. The next step now would be taking these as input and compute the pixel coordinates.
<script>
function initMap() {41.85, -87.65
var myLatlng = {lat: 41.85, lng: -87.65};
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 18,
center: myLatlng,
disableDefaultUI: false,
mapTypeId: 'satellite',
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: false,
rotateControl: false,
fullscreenControl: true});
map.setOptions({draggableCursor:'default'});
map.addListener('click', function(marker){
marker = new google.maps.Marker({map: map,
clickable: false,
position: marker.latLng,
})
var markerposLat = marker.getPosition().lat();
var markerposLon = marker.getPosition().lng();
function pixl(markerposLat,markerposLon){
var projection = map.getProjection();
var bounds = map.getBounds();
var topRight = projection.fromLatLngToPoint(bounds.getNorthEast());
var bottomLeft = projection.fromLatLngToPoint(bounds.getSouthWest());
var scale = Math.pow(2, map.getZoom());
var worldPoint = projection.fromLatLngToPoint(markerposLat,markerposLon);
return [Math.floor((worldPoint.x - bottomLeft.x) * scale), Math.floor((worldPoint.y - topRight.y) * scale)]
};
localStorage["pixl"] = JSON.stringify(pixl);
localStorage["markerLat"] = JSON.stringify(markerposLat);
localStorage["markerLon"] = JSON.stringify(markerposLon);
console.log(localStorage["pixl"],localStorage["markerLat"], localStorage["markerLon"]);
});
}
</script>
Function pixl is always undefined. I realize it's a question that have been asked many times. In fact I've tried to adapt many methods. My starting points are this: convert-lat-lon-to-pixels-and-back and of course this: showing pixel and tile coordinates. I can't spot the problem.
Please note that the fromLatLngToPoint method requires a google.maps.LatLng class as its parameter. From the documentation:
fromLatLngToPoint(latLng[, point])
Parameters:
latLng: LatLng
point: Point optional
Return Value: Point optional
Translates from the LatLng cylinder to the Point plane. This interface specifies a function which implements translation from given LatLng values to world coordinates on the map projection. The Maps API calls this method when it needs to plot locations on screen. Projection objects must implement this method, but may return null if the projection cannot calculate the Point.
So in your code, I would do it this way instead:
var worldPoint = projection.fromLatLngToPoint(marker.getPosition());
Another thing I (and #geocodezip) noticed is that you are not passing a parameter to your pixl function. This is why it is intended for you to get an undefined response. You should include a parameter like below instead in order to get the correct value:
localStorage["pixl"] = JSON.stringify(pixl((markerposLat,markerposLon)));
Here is the working fiddle for this.
I have this string
[['Kaufen Kaufen', 11.6024872, 50.96389749999999, 1], ['Demandware', -71.13296849999999, 42.4884618, 2],['Downtown TV Shop', -71.0661193, 42.3548561, 3], ['Electronics Super Store', -73.21165839999999, 41.1687117, 4],['Super Electronics', -71.40915629999999, 41.816736, 5]]
which is already in array form but it is string I want to convert it into javascript array because I am getting issue with google map to show pin in google map.
var locations = 'javascript array here';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(11.60, 50.96),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
You can use JSON.parse to convert JSON to JS Objects/Arrays. Now issue is, your string has single quotes' and JSON.parse expects double quotes, so you will have to replace it.
Another case can be, you can have single quotes in string itself. For such cases you should check if its not followed by any character.
To depict such case, I have updated your string as 'Kaufen Kaufe'n'
Sample
var str="[['Kaufen Kaufe'n', 11.6024872, 50.96389749999999, 1], ['Demandware', -71.13296849999999, 42.4884618, 2],['Downtown TV Shop', -71.0661193, 42.3548561, 3], ['Electronics Super Store', -73.21165839999999, 41.1687117, 4],['Super Electronics', -71.40915629999999, 41.816736, 5]]";
console.log(JSON.parse(str.replace(/'(?![a-z])/g, '"')));
function stringToArray(str) {
return JSON.parse(str.replace(/'/g, '"'))
}
I'm writing some Google Maps API v3 code, which seems to work just fine with multiple markers, but when there's only 1, it always plots the marker in the top left of the map, just beyond the visible area:
Here's my coffeescript code:
class SimpleMap
constructor: (div_id, lat = 40.783627, lng = -73.942583) ->
# L.Icon.Default.imagePath = "/assets"
#div_id = div_id
#map_options = {center: new google.maps.LatLng(lat, lng), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP}
#markers = []
#map = new google.maps.Map document.getElementById(div_id), #map_options
#loadMarkers() # gets them and plots on the map
#autoFit()
loadMarkers: ->
items = $(".grid-item[data-lat], .apartment[data-lat]")
for item in items
console.log "Adding #{item}"
#addMarker(item)
#autoFit()
addMarker: (item) ->
console.log "Adding marker"
lat = $(item).attr("data-lat")
lng = $(item).attr("data-lng")
console.log "#{lat}, #{lng}"
marker = new google.maps.Marker(
position: new google.maps.LatLng lat, lng
map: #map
title: "This is my marker"
)
#markers.push marker
autoFit: ->
bounds = new google.maps.LatLngBounds()
for marker in #markers
bounds.extend marker.getPosition()
#map.fitBounds bounds
# if you leave out the below, the marker appears int he same position as in the screenshot (slightly off screen) but at the max zoom level.
listener = google.maps.event.addListener(#map, "idle", =>
#map.setZoom 9 if #map.getZoom() > 8
#map.setCenter #markers[0].getPosition()
google.maps.event.removeListener listener
)
The map seems to ignore my attempts to set setCenter(#markers[0].getPosition()). Any ideas?
I believe the issue is in:
bounds = new google.maps.LatLngBounds()
for marker in #markers
bounds.extend marker.getPosition()
#map.fitBounds bounds
where you are extending the current map bounds to include all markers, but you have only one marker, the bounds will extend in a way that the marker will be in the map limit border.
Regards
Following the comments this issue occurs only when there is 1 marker.
Based on this fact I would neardown the problem to this line:
#map.fitBounds bounds
When there is only 1 marker, the NE-corner of bounds is equal to the SW-corner.
I noticed unexpected interactions when you use bounds as fitBounds()-argument in this case.
Suggestion:
only use fitBounds() when there are at least 2 markers.
I have a webpage that receives AJAX data with values listing_id, lat, lng using $.getJSON. The callback function takes these series of values and creates a Google map marker for each set of listing_id, lat, lng. The marker is then pushed into an array markers and its listing_id into an array markersListingId.
var latLng = new google.maps.LatLng(json[i].lat, json[i].lng);
var marker = new google.maps.Marker({
position: latLng,
icon: base_url + 'images/template/markers/listing.png',
});
markers.push(marker);
markersListingId.push(json[i].listing_id);
Problem: The problem arises when I want to select a specific Marker that corresponds to a particular listing_id, especially in more complicated situations with markers being deleted and added to the markers array.
I can have for loops looping through all the marker's id in markersListingId array then using the loop's index i to get the marker in markers array, but this will make tracking very tricky.
var id_to_select = 1234;
for(var i = 0; i < markersListingId; i++) {
if(markersListingId[i] == id_to_select) {
markers[i].setMap(null);
}
}
Question: How can I store the markers so that I can easily select a specific marker by using its listing_id?
When you create the markers, instead of using an array, can you use a hash table?
http://jsfiddle.net/j9J8x/
var markers = {};
//id goes in place of 1234
n = 1234;
markers[n] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(0,0)
});
s = '2234'
markers[s] = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(20,0)
});
google.maps.event.addListener(map, 'click', function(event) {
k = 1234;
markers[k].setMap(null);
markers['2234'].setMap(null);
});
}
I have 19 postal codes in an array which go through GeoCode, it seems to work fine but only 11 of them get displayed. I have searched and tried everything. I have only just started learning JavaScript and the map API, so I'm sure my spelling is wrong on something.
var latlng = new google.maps.LatLng(55.378, -3.435);
myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("my_canvas"),myOptions);
var geocoder = new google.maps.Geocoder();
var places = ["AB12 3AG","BS11 8AT","IG11 0HN","CA3 0PJ","NR19 1JG","IP11 3HZ","ML4 3LR","WF12 7TH","L33 7YE","M30 9QG","NG18 5DQ","MK12 5QL","PE6 0BN","ME10 3RL","SO40 9HN","B79 7TD","TS2 1RP","GU17 0NP","WV10 7EL"];
for(i = 0; i < places.length; i++){
var address = places[i];
geocoder.geocode({'address':address}, function(results){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: address
});
});
}
I think that all the post codes do load because the title for all the markers is the last address in the array 'WV10', but like I said, only 11 out of the 19 locations get displayed.
The problem is that you are creating a function in a loop. At least this is the problem for the label. A solution for this is to create a new scope be calling a function inside the loop:
for(i = 0; i < places.length; i++){
(function(place) {
geocoder.geocode({'address':place}, function(results){
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: place
});
});
}(places[i]));
}
This might also solve the display problem, but I'm not sure about this. Could it be that some places resolve to the same or very close positions?