Andrew Andrew - 4 months ago 23
Javascript Question

Google Map issue addressing location from DB

this line is not working and no error in console.

position: new google.maps.LatLng( coordsArray[i].location ),


data confirmed by
alert(coordsArray[i].location);
location been database field returning LatLng -43.59670,172.38247 as a string.

This line works:
position: new google.maps.LatLng( -43.59670,172.38247 ),

What is the same data as above, any ideas what wrong with my code?



var list_location = localStorage.getItem('myHouse');
var obj = JSON.parse(list_location);
var coordsArray = obj;
var marker;
var locX;
var image = 'http://apppics.weebly.com....png';
var map = Appery("googlemap_6").options.mapElement.gmap('get', 'map');


var CreateMarker = function(coordsArray, i){
var marker = new google.maps.Marker({
position: new google.maps.LatLng( coordsArray[i].location ),
//position: new google.maps.LatLng( -43.59670,172.38247 ),

title: coordsArray[i].storeName,
map: Appery("googlemap_6").gmap,
});

for (var i = 0, j = coordsArray.length; i < j-1; i++)
alert(coordsArray[i].location);
CreateMarker(coordsArray, i);




Answer

This is incorrect: new google.maps.LatLng(coordsArray[i].location).

You state: "location been database field returning LatLng -43.59670,172.38247 as a string."

the google.maps.LatLng constructor takes two numbers as arguments (not a comma separated string).

If coordsArray[i].location is a comma separated string, convert it to two numbers.

var coords = coordsArray[i].location.split(",");
var latLng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
var marker = new google.maps.Marker({
  position: latLng,
  map: map
});

code snippet:

var geocoder;
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var location = "-43.59670,172.38247";
  coords = location.split(",");
  var latLng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
  var marker = new google.maps.Marker({
    position: latLng,
    map: map
  });
  map.setCenter(latLng);

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?"></script>
<div id="map_canvas"></div>