how to convert string into javascript array - javascript

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, '"'))
}

Related

Google Maps script in particular format

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
});
}

Google Maps - get values from location array based on the map's current viewpoint

Edit:
Question = "is there a way to loop through the array and check if each location (long/lat) falls within the current viewport directly" (failing that get all markers within the viewport)
Background:
I have an array of locations (lat, long, id).
I want to:
On a Google Map, use the location array to display markers.
The user can scroll/zoom the map.
Have a button underneath the map, so when the user has decided on an area, he can click the button, and the code will return the ids (from the location array) that are contained within the viewport / map bounds.
There is a .contains for Google, so I guess you could potentially use that with something like
map.getBounds().contains and somehow reference each marker.getPosition()
but I wonder if there's a way to loop through the array and check if each location (long/lat) falls within the current viewport directly
You mean something like this (not tested), map is the google.maps.Map object and needs to be in scope. markersArray is the array of markers.
for (var i=0; i< markersArray.length; i++) {
if (map.getBounds().contains(markersArray[i].getPosition())) {
// the marker is in view
} else {
// the marker is not in view
}
}
http://jsfiddle.net/UA2g2/1/
Thanks geocodezip, you gave me the idea on how to solve it via looping through the array. I don't know if this is the most efficient way, but I put together some code that seems to do what I want - if you check the jsfiddle above and view console you can see that it logs when and which points are in the viewport.
$(document).ready(function(){
var myOptions = {
center: new google.maps.LatLng(51, -2),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var storeArray = new Array(["51.38254", "-2.362804", "ID1"], ["51.235249", "-2.297804","ID2"], ["51.086126", "-2.910767","ID3"]);
google.maps.event.addListener(map, 'idle', function() {
for (i = 0; i < storeArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(storeArray[i][0], storeArray[i][1]),
map: map
});
}
for (var i=0; i<storeArray.length; i++) {
if (map.getBounds().contains(new google.maps.LatLng(storeArray[i][0], storeArray[i][1]))) {
console.log("marker: " + storeArray[i][2]);
}
}
});
});

Google Maps v3 Marker Always Appears at Top Left

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.

Storing Google Map Markers and Selecting a specific marker from it

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);
});
}

google maps v3 not displaying all markers

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?

Categories

Resources